LINQ .First(), .Last(), .Single() method throws an error if there are no records

Posted: November 20, 2008 in ASP.NET, LINQ
Tags: , , , ,

So….. I have used the .First() method in many of my LINQ queries to make sure that my query only returns one record.  I thought this would be a great way to insure isolation of one record.  Very similar to a TOP 1 statement in SQL.  However, there is an issue with this concept.  If your TOP 1 SQL statement doesn’t find any records it returns nothing.  I guess I sort of hoped that the .First() method would do something similar – say return NULL or something like that.  It doesn’t!  Instead it throws an error stating “InvalidOperationException : sequence contains no elements”.  Not what I had hoped for.

No worries though!  There apparently was a reason for this method to find 1 or flip out as the LINQ team also provides the FirstOrDefault() method which will return NULL if no records were found.  Their documentation on the 101 LINQ Samples page doesn’t state anything about throwing an error.  It doesn’t really state anything at all about what would happen if the First() item wasn’t found.  It does state however that the FirstOrDefault() method will return the default value for the requested type – IE NULL!

You can face above errors on using .First(), .Last(), or .Single() method to make sure the query returns only single record. You can use .FirstOrDefault(), .LastOrDefault(), or .SingleOrDefault() instead.

Happy Programming!!

  1. maxi326 says:

    as a newbie to LINQ.
    glad to know these stuff.

  2. khatwai says:

    thanks for LastOrDefault()

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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