Enumerable.ElementAt<TSource>(IEnumerable<TSource>, Int32) Method


返回序列中指定索引处的元素。Returns the element at a specified index in a sequence.

generic <typename TSource>
 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
Public Function ElementAt(Of TSource) (source As IEnumerable(Of TSource), index As Integer) As TSource

Type Parameters


source 的元素类型。The type of the elements of source.



要从中返回元素的 IEnumerable<T>An IEnumerable<T> to return an element from.


要检索的从零开始的元素索引。The zero-based index of the element to retrieve.



源序列中指定位置处的元素。The element at the specified position in the source sequence.


sourcenullsource is null.

index 小于零或大于等于 source 中的元素数量。index is less than 0 or greater than or equal to the number of elements in source.


下面的代码示例演示如何使用 ElementAt 返回位于特定位置的元素。The following code example demonstrates how to use ElementAt to return an element at a specific position.

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 the following sample output:

 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 the following output:
' The name chosen at random is Ito, Shu


如果 source 的类型实现 IList<T>,则该实现用于获取指定索引处的元素。If the type of source implements IList<T>, that implementation is used to obtain the element at the specified index. 否则,此方法将获取指定的元素。Otherwise, this method obtains the specified element.

如果 index 超出范围,则此方法将引发异常。This method throws an exception if index is out of range. 如果指定的索引超出范围,则改为返回默认值,请使用 ElementAtOrDefault 方法。To instead return a default value when the specified index is out of range, use the ElementAtOrDefault method.

Applies to