Enumerable.ElementAtOrDefault 方法

定义

重载

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

返回序列中指定索引处的元素;如果索引超出范围,则返回默认值。

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

返回序列中指定索引处的元素;如果索引超出范围,则返回默认值。

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

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

返回序列中指定索引处的元素;如果索引超出范围,则返回默认值。

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

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

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

index
Index

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

返回

TSource

default 如果 index 超出序列的 source 边界,则为 ;否则为序列中指定位置处的 source 元素。

例外

sourcenull

注解

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

引用和可为空类型的默认值为 null

适用于

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

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

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

返回序列中指定索引处的元素;如果索引超出范围,则返回默认值。

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

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

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

index
Int32

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

返回

TSource

如果索引超出源序列的边界,则为 default(TSource);否则为源序列中指定位置处的元素。

例外

sourcenull

示例

下面的代码示例演示如何使用 ElementAtOrDefault。 此示例使用数组边界之外的索引。

C#
string[] names =
    { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
        "Hedlund, Magnus", "Ito, Shu" };

int index = 20;

string name = names.ElementAtOrDefault(index);

Console.WriteLine(
    "The name chosen at index {0} is '{1}'.",
    index,
    String.IsNullOrEmpty(name) ? "<no name at this index>" : name);

/*
 This code produces the following output:

 The name chosen at index 20 is '<no name at this index>'.
*/

注解

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

引用和可为空类型的默认值为 null

适用于

.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