Enumerable.ElementAt<TSource>(IEnumerable<TSource>, Int32) 方法
定义
返回序列中指定索引处的元素。Returns the element at a specified index in a sequence.
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
的元素类型。The type of the elements of source
.
参数
- source
- IEnumerable<TSource>
要从中返回元素的 IEnumerable<T>。An IEnumerable<T> to return an element from.
- index
- Int32
要检索的从零开始的元素索引。The zero-based index of the element to retrieve.
返回
- TSource
源序列中指定位置处的元素。The element at the specified position in the source sequence.
例外
source
为 null
。source
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.