What is difference between First and FirstOrDefault in LINQ?

Last week I were presenting LINQ to group of almost 100 audience. While writing query a question raised that what is difference between First and FirstOrDefault . At that time I was not very sure about answer so I asked audience to help me. One from audience answered this question. So credit of this blog to him. For benefit of all I am documenting answer below,

Let us focus on answer of this question. I am sure that you may have come across following query in LINQ.

In below query we are fetching First record on given condition.

image

Now there are two kind of result you can expect.

  • Either a product on basis of criteria
  • Or there is no product on given criteria

If there is no product on the critera you are searching then LINQ will throw you run time exception of type InvalidOperationException

image

So when you are working with First() make sure that you have handled the InvalidOperationException else you may encounter exception if there is no result matched on given criteria. So you may want to modify code as given below,

try
 {
 Product result = (from r in GetProducts()
 where
 r.ProductId == 1
 select r).First();
 }
 catch (InvalidOperationException ex)
 {
 Console.WriteLine(ex.Message);
 }

If there is no match then you will get output as below,

clip_image002

Next option is FirstOrDefault . So you may have come across following query. If there is no Product matched on given criteria then LINQ will return NULL.

image

So assume there is not matched Product and query has returned NULL then in that case if you access result then you will get exception as following

image

To avoid run time NullReferenceException you can modify code as following,

Product result1 = (from r in GetProducts()
 where
 r.ProductId == 1
 select r).FirstOrDefault() ;
 if (result1 != null)
 {
 Console.WriteLine(result1.ProductPrice);
 }

else
 {
 Console.WriteLine("No Record Found");
 }

 

Now when there is no Product code will gracefully print a message that No Record Found. This is basic difference between First and FirstOrDefualt. I hope you find this post useful. Thanks for reading.

6 responses to “What is difference between First and FirstOrDefault in LINQ?”

  1. Thanks sir….

  2. Another great one. Its really interesting how you add new knowledge in every post! Thanks.

  3. Dhananjay Kumar

    Glad you like it

  4. Note that if you are going to return the whole record (i.e. “…. select r”) You’d probably be better off using the lambda syntax instead of the LINQ syntax:

    lambda:
    Product result1 =GetProducts().FirstOrDefault(r=> r.ProductId == 1);

    LINQ:
    Product result1 = (from r in GetProducts()
    where r.ProductId == 1
    select r).FirstOrDefault() ;

  5. Amol Kumbhkarna

    Very useful Thanks for sharing it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com