Linq:First()与FirstOrDefault()的区别
来源:互联网 发布:手机号数据库 编辑:程序博客网 时间:2024/06/04 19:09
First() and FirstOrDefault() are two extension methods of the Enumerable class. Extension method is a static method that we can call from an instance object which implement IEnumerable interface. Lets make an analysis of the following simple example.
int[] number = { 1, 5, 6, 8, 20, 15, 34, 67, 98, 12, 23 };
var num = number.Where(n => n > 100).First();
Console.WriteLine("First Number greater than 100: {0}", num);
By definition, First() method return the first element of a sequence. So if we run this code, it throws an error:
InvalidOperationException was unhandled
The error occurs because the sequence returned by the Where method contains no element.The First() method should be used when sequence contains at least one element, otherwise it throws an exception.
How to prevent this exception to happen:
We have two choices:
- instead of "First()", use "FirstOrDefault()" that return default value whether sequence has no elements.
var num = number.Where(n => n > 100).FirstOrDefault();
The default value depend type of the element in sequence. Here the type is int so the default element is 0 (zero).
As output, we have something like: First Number greater than 100 : 0
What's happened if the type is an instance object? In this case, the defaut value is null.
- or, setting the default value by using "DefaultIfEmpty()" method extension before call "First()" method.
var num = number.Where(n => n > 100).DefaultIfEmpty(100).First();
As output, we have something like: First Number greater than 100 : 100
Conclusion
The “First()” extension method should be used with precaution. Keep in mind that if the sequence might be empty, the best alternative is to use one of the two choice above.
- Linq:First()与FirstOrDefault()的区别
- C# Linq First 和 FirstOrDefault的区别
- Find()和First()与FirstOrDefault()区别
- First,FirstOrDefault,Single,SingleOrDefault 的区别
- First,FirstOrDefault,Single,SingleOrDefault的区别
- First,FirstOrDefault,Single,SingleOrDefault的区别
- Linq: First,FirstOrDefault,Single,SingleOrDefault
- First and FirstOrDefault 区别
- First,FirstOrDefault,Single,SingleOrDefault 区别
- LINQ :First、FirstOrDefault使用;Max、Min使用
- LINQ :First、FirstOrDefault使用;Max、Min使用
- linq语法之Where First、FirstOrDefault Single...
- LINQ :First、FirstOrDefault使用;Max、Min使用
- LINQ :First、FirstOrDefault使用;Max、Min使用
- .NET中First,FirstOrDefault,Single,SingleOrDefault的区别是什么
- First、FirstOrDefault 、Single和SingleOrDefault的区别 (转)
- Linq中SingleOrDefault、FirstOrDefault的用法
- Linq中SingleOrDefault、FirstOrDefault的用法
- 在JSP中 中文的编码详解 gb2312 GBK UTF-8
- Linux ALSA声卡驱动之六:ASoC架构中的Machine
- 研发产品介绍2:开心逍遥笔授权——搜狗PC输入法
- WM_CTLCOLOR和OnCtlColor消息的用法
- scheduler与job的异同
- Linq:First()与FirstOrDefault()的区别
- Linux ALSA声卡驱动之七:ASoC架构中的Codec
- 用qemu-mini2440仿真rtems时的小问题
- MySQL float,double,decimal数据类型区别
- 数据库分页语句
- java中HashMap详解
- Linux ALSA声卡驱动之八:ASoC架构中的Platform
- 鄙人最新作,购物车程序完善版
- java 捕获线程里抛出的异常