Enumerable.Last 方法

定義

傳回序列的最後一個項目。

多載

Last<TSource>(IEnumerable<TSource>)

傳回序列的最後一個項目。

Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的最後一個元素。

Last<TSource>(IEnumerable<TSource>)

來源:
Last.cs
來源:
Last.cs
來源:
Last.cs

傳回序列的最後一個項目。

C#
public static TSource Last<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

類型參數

TSource

source 項目的類型。

參數

source
IEnumerable<TSource>

要傳回最後一個項目的 IEnumerable<T>

傳回

TSource

位於來源序列中最後一個位置的值。

例外狀況

sourcenull

來源序列為空。

範例

下列程式代碼範例示範如何使用 Last<TSource>(IEnumerable<TSource>) 傳回數位的最後一個專案。

C#
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
                    83, 23, 87, 67, 12, 19 };

int last = numbers.Last();

Console.WriteLine(last);

/*
 This code produces the following output:

 19
*/

備註

如果source不包含任何元素,方法Last<TSource>(IEnumerable<TSource>)會擲回例外狀況。 若要改為在來源序列是空的時傳回預設值,請使用 LastOrDefault 方法。

適用於

.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

Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

來源:
Last.cs
來源:
Last.cs
來源:
Last.cs

傳回序列中符合指定之條件的最後一個元素。

C#
public static TSource Last<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,bool> predicate);

類型參數

TSource

source 項目的類型。

參數

source
IEnumerable<TSource>

傳回項目的 IEnumerable<T>

predicate
Func<TSource,Boolean>

用來測試每個項目是否符合條件的函式。

傳回

TSource

序列中通過指定之述詞函式所做測試的最後一個項目。

例外狀況

sourcepredicatenull

沒有任何項目符合 predicate 的條件。

-或-

來源序列為空。

範例

下列程式代碼範例示範如何使用 Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 傳回符合條件之陣列的最後一個專案。

C#
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
                    83, 23, 87, 67, 12, 19 };

int last = numbers.Last(num => num > 80);

Console.WriteLine(last);

/*
 This code produces the following output:

 87
*/

備註

如果在 中source找不到相符的專案,方法Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)會擲回例外狀況。 若要改為在找不到相符的項目時傳回預設值,請使用 LastOrDefault 方法。

適用於

.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