Enumerable.ElementAtOrDefault<TSource> Метод

Определение

Возвращает элемент по указанному индексу в последовательности или значении по умолчанию, если индекс выходит из диапазона.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource ElementAtOrDefault(System::Collections::Generic::IEnumerable<TSource> ^ source, int index);
public static TSource ElementAtOrDefault<TSource>(this System.Collections.Generic.IEnumerable<TSource> source, int index);
static member ElementAtOrDefault : seq<'Source> * int -> 'Source
<Extension()>
Public Function ElementAtOrDefault(Of TSource) (source As IEnumerable(Of TSource), index As Integer) As TSource

Параметры типа

TSource

Тип элементов source.

Параметры

source
IEnumerable<TSource>

Объект IEnumerable<T> , из который возвращается элемент.

index
Int32

Отсчитываемый от нуля индекс элемента.

Возвращаемое значение

TSource

() Значение <a0/>, если индекс находится вне границ исходной последовательности; в противном случае элемент находится в указанной позиции в исходной последовательности.

Исключения

source равно null.

Примеры

В следующем примере кода показано, как использовать ElementAtOrDefault. В этом примере используется индекс, который находится за пределами границ массива.

string[] names =
    { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
        "Hedlund, Magnus", "Ito, Shu" };

int index = 20;

string name = names.ElementAtOrDefault(index);

Console.WriteLine(
    "The name chosen at index {0} is '{1}'.",
    index,
    String.IsNullOrEmpty(name) ? "<no name at this index>" : name);

/*
 This code produces the following output:

 The name chosen at index 20 is '<no name at this index>'.
*/
' Create an array of strings.
Dim names() As String =
{"Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu"}

Dim index As Integer = 20

' Get a string at an index that is out of range in the array.
Dim name As String = names.ElementAtOrDefault(index)

Dim text As String = If(String.IsNullOrEmpty(name), "[THERE IS NO NAME AT THIS INDEX]", name)

' Display the output.
Console.WriteLine($"The name chosen at index {index} is {text}")

' This code produces the following output:
'
' The name chosen at index 20 is [THERE IS NO NAME AT THIS INDEX]

Комментарии

Если тип source реализации IList<T>, эта реализация используется для получения элемента по указанному индексу. В противном случае этот метод получает указанный элемент.

Значением по умолчанию для ссылочных и типы, допускающие значение NULL, является null.

Применяется к