Queryable.ElementAtOrDefault 方法

定義

多載

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

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

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

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

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

來源:
Queryable.cs
來源:
Queryable.cs
來源:
Queryable.cs

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

C#
public static TSource? ElementAtOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, Index index);

類型參數

TSource

source 項目的類型。

參數

source
IQueryable<TSource>

傳回項目的 IQueryable<T>

index
Index

要擷取之專案的索引,從開頭或結尾開始。

傳回

TSource

default 如果 index 位於序列界限 source 之外,則為 ,否則為序列中指定位置的專案 source

例外狀況

sourcenull

適用於

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

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

來源:
Queryable.cs
來源:
Queryable.cs
來源:
Queryable.cs

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

C#
public static TSource ElementAtOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, int index);
C#
public static TSource? ElementAtOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, int index);

類型參數

TSource

source 項目的類型。

參數

source
IQueryable<TSource>

傳回項目的 IQueryable<T>

index
Int32

要擷取的項目之以零為起始索引。

傳回

TSource

default如果 位於的界限外,TSource () index;否則,位於 中指定位置的專案sourcesource

例外狀況

sourcenull

範例

下列程式碼範例將示範如何使用 ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32)。 這個範例會使用 位於來源序列界限外的 值 index

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

int index = 20;

string name = names.AsQueryable().ElementAtOrDefault(index);

Console.WriteLine(
    "The name chosen at index {0} is '{1}'.",
    index,
    String.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name);

/*
    This code produces the following output:

    The name chosen at index 20 is '[NONE AT THIS INDEX]'.
*/

備註

方法 ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) 會產生 , MethodCallExpression 表示呼叫 ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) 本身為建構的泛型方法。 然後,它會將 傳遞給 MethodCallExpressionExecute<TResult>(Expression) 參數之 屬性所Provider表示的方法IQueryProvidersource

執行表示呼叫 ElementAtOrDefault<TSource>(IQueryable<TSource>, Int32) 的表達式樹狀結構所產生的查詢行為,取決於參數類型的實作 source 。 預期的行為是它會在 中的位置index傳回專案,如果 位於 的界限source之外,則default(TSource)indexsource回 。

適用於

.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 2.0, 2.1
UWP 10.0