News


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.

 1:int[] number = { 1, 5, 6, 8, 20, 15, 34, 67, 98, 12, 23 };
 2:var num = number.Where(n => n > 100).First(); 
 3: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.
  •  1: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.
  •  1: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.


Comments

Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by urdu tutorial on 10/29/2011 7:55 PM
Very creative work indeed. I really like this article. You have spent so much time in generating such important contents.
urdu tutorial

Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by mark on 11/18/2011 5:22 AM
Nice article. I've always stayed away from first/first or default because I never knew how to set the default and I'd rather check for null values than catch exceptions. Now I do.
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by saints row 2 cheats on 12/25/2011 5:05 PM
Saint's Row 2 is one of the most popular Xbox 360 games and you can download it form Xbox 360 Download Center for free.
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by amandeep on 2/6/2012 11:30 PM
When turning screen printing from a hobby into a business it will make life a lot easier to invest in a Screen Printing Machine
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by david on 2/14/2012 10:23 AM
Recently I've been wondering which is faster:
To use your example,
var num = number.Where(n => n > 100).First();
OR
var num = number.First(n => n > 100);

The point being: Does linq evaluate the two the same? Or does using the where() with first() at the end act differently? Get all matches, then take the first match, vs get the first match...
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by Berthin on 5/25/2012 8:54 PM
Hi David, thanks for your comment.
The process is different for the two points:
- in the example, Where then First extension methods:
1- Get all matches elements into a IEnumerable<int>
2- Then from the IEnumerable<int>, Linq returns directly the first match element
- whereas First with predicate return directly the first match element.

So in this point of view, the second case is fast.
Nevertheless, in some cases you want to have, for example, the smallest number that meets the condition, in this case you need to use "where" then "First" extension methods.

Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by friendship bracelet on 10/15/2012 3:57 PM
it is very useful for me
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by Habi on 11/16/2012 9:28 PM
Nice Article.
this explains more about the use or first() and firstordefault().
http://dotnet-programming-solutions.blogspot.com/2012/10/when-to-use-first-and-firstordefault.html
Gravatar # re: Linq: How to use First() and FirstOrDefault() methods properly
Posted by Habi on 11/16/2012 9:31 PM
Nice Article.
this explains more about the use or
first() and firstordefault().
Gravatar # adsense site
Posted by buy adsense account on 11/6/2013 11:38 PM
First() and FirstOrDefault() methods are being used still in codes? Anyways nice information. To get buy adsense account
Comments have been closed on this topic.