Geeks With Blogs
Berthin Ramampiandra

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.

Posted on Friday, July 22, 2011 9:30 PM Linq | Back to top


Comments on this post: Linq: How to use First() and FirstOrDefault() methods properly

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

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
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.
Left by mark on Nov 18, 2011 5:22 AM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
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.
Left by saints row 2 cheats on Dec 25, 2011 5:05 PM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
When turning screen printing from a hobby into a business it will make life a lot easier to invest in a Screen Printing Machine
Left by amandeep on Feb 06, 2012 11:30 PM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
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...
Left by david on Feb 14, 2012 10:23 AM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
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.
Left by Berthin on May 25, 2012 8:54 PM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
it is very useful for me
Left by friendship bracelet on Oct 15, 2012 3:57 PM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
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
Left by Habi on Nov 16, 2012 9:28 PM

# re: Linq: How to use First() and FirstOrDefault() methods properly
Requesting Gravatar...
Nice Article.
this explains more about the use or
first() and firstordefault().
Left by Habi on Nov 16, 2012 9:31 PM

# adsense site
Requesting Gravatar...
First() and FirstOrDefault() methods are being used still in codes? Anyways nice information. To get buy adsense account
Left by buy adsense account on Nov 06, 2013 11:38 PM

Comments have been closed on this topic.
Copyright © berthin | Powered by: GeeksWithBlogs.net | Join free