C# First and FirstOrDefault 方法詳解

在工做中咱們常常會遇到有關LINQ 的一些問題。這時咱們就用到lambda 表達式。數組

下面是我在工做遇到的。 First  and FirstOrDefault  這兩方法。我今天把它記錄一下。this

須要注意的是我標註紅色的部分,這是它們倆的區別。spa

First  and FirstOrDefault 

 1 #region
Enumberable First() or FirstOrDefault()
 2         /// <summary>
 3         /// 返回序列中的第一個元素;若是序列中不包含任何元素,則返回默認值。 
 4         /// 若是 source 爲空,則返回 default(TSource);不然返回 source 中的第一個元素。
 5         /// ArgumentNullException      sourcevalue 爲 null。
 6         /// </summary>
 7         public static void FunFirstOrDefault()
 8         {
 9             //FirstOrDefault()
10             string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };
11             // string[] names = { }; // string 類型的默認值是空
12 
13             int[] sexs = { 100, 229, 44, 3, 2, 1 };
14             // int[] sexs = { };  // 由於int 類型的默認值是0. 因此當int[] 數組中沒有任何元素時。default value is 0; 若是有元素,則返回第一個元素
15 
16             //原方法: public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);   // 擴展了IEnumerable<TSource>  接口
17             //string namevalue = names.FirstOrDefault();  // string IEnumerable<string>.FirstOrDefault<string>();
18             int sexvalue = sexs.FirstOrDefault(); // int IEnumerable<int>.FirstOrDefault<string>();
19             //string namevalue = names.DefaultIfEmpty("QI").First();
20             string namevalue = names.FirstOrDefault();
21             Console.WriteLine("FirstOrDefault(): default(TSource) if source is empty; otherwise, the first element in source:{0}", namevalue);
22 
23 
24         }
25 
26         /// <summary>
27         /// 返回序列中的第一個元素。 
28         /// 若是 source 中不包含任何元素,則 First<TSource>(IEnumerable<TSource>) 方法將引起異常
29         /// ArgumentNullException      sourcevalue 爲 null。
30         //  InvalidOperationException  源序列爲空。
31         /// </summary>
32         public static void FunFirst()
33         {
34             //First()
35             string[] names = { "Haiming QI", "Har", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu", null };
36             // string[] names = { };
37 
38             int[] sexs = { 100, 229, 44, 3, 2, 1 };
39             //int[] sexs = { };
40             int fsex = sexs.First();
41             string fname = names.First(); // 若是序列中沒有元素則會發生,InvalidOperationException 異常。 源序列爲空。
42 
43             Console.WriteLine("First(): Returns the first element of a sequence : {0}", fname);
44 
45         }
46         #endregion

以上是我在本地驗證的code.code

須要注意的是:blog

 

這都是擴展了IEnumerable 這個接口。接口

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);

First 和 FirstOrDefault 最大的區別在於。 當集合(這個集合能夠是:Arry,List,等等)中沒有元素的時候。 First 會報異常 InvalidOperationException 源序列爲空。
而 FirstOrDefault 則不會。
相關文章
相關標籤/搜索