Linq:First()与FirstOrDefault()的区别

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.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值