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.

原创粉丝点击