Enumerable.ElementAt 方法

定义

重载

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

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

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

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

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

Source:
ElementAt.cs
Source:
ElementAt.cs
Source:
ElementAt.cs

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

C#
public static TSource ElementAt<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Index index);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

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

index
Index

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

返回

TSource

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

例外

sourcenull

index 超出了序列的 source 边界。

注解

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

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

适用于

.NET 9 和其他版本
产品 版本
.NET 6, 7, 8, 9

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

Source:
ElementAt.cs
Source:
ElementAt.cs
Source:
ElementAt.cs

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

C#
public static TSource ElementAt<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, int index);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

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

index
Int32

要检索的从零开始的元素索引。

返回

TSource

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

例外

sourcenull

index 小于零或大于等于 source 中的元素数量。

示例

下面的代码示例演示如何使用 ElementAt 返回位于特定位置的元素。

C#
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'.
*/

注解

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

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

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0