Enumerable.ElementAt 方法

定义

重载

ElementAt<TSource>(IEnumerable<TSource>, Index)

返回序列中指定索引处的元素。

ElementAt<TSource>(IEnumerable<TSource>, Int32)

返回序列中指定索引处的元素。

ElementAt<TSource>(IEnumerable<TSource>, Index)

返回序列中指定索引处的元素。

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

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

要从中返回元素的 IEnumerable<T>

index
Index

要检索的元素的索引,该索引是从序列的开头或结尾。

返回

TSource

序列中指定位置处的 source 元素。

例外

source 上声明的默认值为 null

index 位于序列边界 source 之外。

注解

如果实现的类型 source ,则使用该实现 IList<T>获取指定索引处的元素。 否则,此方法将获取指定的元素。

如果 index 范围不足,此方法将引发异常。 若要在指定索引超过范围时返回默认值,请使用 ElementAtOrDefault 该方法。

适用于

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

源序列中指定位置处的元素。

例外

sourcenull

index 小于零或大于等于 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 该方法。

适用于