C# First and FirstOrDefault 方法详解

在工作中我们经常会遇到有关LINQ 的一些问题。这时我们就用到lambda 表达式。

下面是我在工作遇到的。 First  and FirstOrDefault  这两方法。我今天把它记录一下。

需要注意的是我标注红色的部分,这是它们俩的区别。

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.

需要注意的是:

这都是扩展了IEnumerable 这个接口。

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

First 和 FirstOrDefault 最大的区别在于。 当集合(这个集合可以是:Arry,List,等等)中没有元素的时候。 First 会报异常 InvalidOperationException 源序列为空。
而 FirstOrDefault 则不会。
原文地址:https://www.cnblogs.com/htwdz-qhm/p/4107906.html