Search
Close this search box.

Linq: How to use First() and FirstOrDefault() methods properly

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();
  • or, setting the default value by using “DefaultIfEmpty()” method extension before call “First()” method.
var num = number.Where(n => n > 100).DefaultIfEmpty(100).First(); 

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.

posted @ Friday, July 22, 2011 9:30 PM | Filed Under [ Linq ]

This article is part of the GWB Archives. Original Author: Berthin Ramampiandra

Related Posts