Enumerable.ElementAtOrDefault 方法

定義

多載

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

傳回位於序列中指定索引處的元素;如果索引超出範圍,則傳回預設值。

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

傳回位於序列中指定索引處的元素;如果索引超出範圍,則傳回預設值。

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

來源:
ElementAt.cs
來源:
ElementAt.cs
來源:
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 型別預設值為 null

適用於

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

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

來源:
ElementAt.cs
來源:
ElementAt.cs
來源:
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 型別預設值為 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