LINQ 元素運算符 Last和LastOrDefault

元素運算符描述
Last返回集合中的最后一個元素,或滿足條件的最后一個元素
LastOrDefault返回集合中的最后一個元素,或滿足條件的最后一個元素。如果不存在這樣的元素,則返回默認值。

Last和LastOrDefault具有兩個重載方法。一個重載方法不使用任何輸入?yún)?shù),而是返回集合中的最后一個元素。第二個重載方法使用lambda表達式指定條件,然后返回滿足指定條件的最后一個元素。

Last() 和 LastOrDefault()重載:
public static TSource Last<TSource>(this IEnumerable<TSource> source);
public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Last()方法從集合中返回最后一個元素,或者使用lambda表達式或Func委托返回滿足指定條件的最后一個元素。如果給定的集合為空或不包含任何滿足條件的元素,則它將拋出 InvalidOperation 異常。

LastOrDefault()方法與Last()方法具有相同的作用。唯一的區(qū)別是,如果集合為空或找不到滿足條件的任何元素,它將返回集合數(shù)據(jù)類型的默認值。

下面的示例演示Last()方法。

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("intList中的最后一個元素: {0}", intList.Last());

Console.WriteLine("intList中的最后一個偶數(shù): {0}", intList.Last(i => i % 2 == 0));

Console.WriteLine("strList中的最后一個元素: {0}", strList.Last());

Console.WriteLine("emptyList.Last()拋出InvalidOperationException ");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.Last());
輸出:
intList中的最后一個元素:
intList中的最后一個偶數(shù):50 
strList中的最后一個元素:5
emptyList.Last()拋出InvalidOperationException 
----------------------------------------------- --------------
Run-time exception: Sequence contains no elements...
下面的示例演示LastOrDefault()方法。
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("intList中的最后一個元素: {0}", intList.LastOrDefault());
Console.WriteLine("intList中的最后一個偶數(shù)元素: {0}",intList.LastOrDefault(i => i % 2 == 0));
Console.WriteLine("strList中的最后一個元素: {0}", strList.LastOrDefault());
Console.WriteLine("emptyList中的最后一個元素: {0}", emptyList.LastOrDefault());
輸出:
intList中的最后一個元素:
intList中的最后一個偶數(shù)元素:10 
strList中的最后一個元素:
emptyList中的最后一個元素:

在Last()或LastOrDefault()中指定條件時要小心。如果集合不包含任何滿足指定條件的元素或包含null元素,那么Last()將拋出異常。

如果集合包含null元素,則LastOrDefault()在評估指定條件時會引發(fā)異常。以下示例對此進行了演示。

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
		
Console.WriteLine("intList中大于250的最后一個元素: {0}", intList.Last(i => i > 250));

Console.WriteLine("intList中的最后一個偶數(shù)元素: {0}", strList.LastOrDefault(s => s.Contains("T")));
輸出:
Run-time exception: Sequence contains no matching element          
//運行時異常:序列不包含匹配元素
丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清