Enumerable.ElementAt<TSource>(IEnumerable<TSource>, Int32) Метод

Определение

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

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

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

TSource

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

Параметры

source
IEnumerable<TSource>

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

index
Int32

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

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

TSource

Элемент в указанной позиции в исходной последовательности.

Исключения

source равно null.

index значение меньше 0 или больше или равно числу элементов в source.

Примеры

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

string[] names =
    { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",

        "Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);

string name = names.ElementAt(random.Next(0, names.Length));

Console.WriteLine("The name chosen at random is '{0}'.", name);

/*
 This code produces output similar to the following:

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

Dim random As Random = New Random(DateTime.Now.Millisecond)

' Get a string at a random index within the array.
Dim name As String = names.ElementAt(random.Next(0, names.Length))

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

' This code produces output similar to the following:
'
' The name chosen at random is Ito, Shu

Комментарии

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

Этот метод создает исключение, если index оно выходит за пределы диапазона. Чтобы вместо этого вернуть значение по умолчанию, если указанный индекс выходит из диапазона, используйте ElementAtOrDefault метод.

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