Blog Stats
  • Posts - 59
  • Articles - 0
  • Comments - 128
  • Trackbacks - 0

 

LINQ .First() method throws an error if there are no records!

Egad!  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 "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!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: LINQ .First() method throws an error if there are no records!

Gravatar You can use (query statement).Take(1) for Top 1 9/22/2008 8:08 AM | Paul Cookson

# re: LINQ .First() method throws an error if there are no records!

Gravatar Or better is use of (query statement).FirstOrDefault() 2/15/2009 3:29 AM | Milos Chaloupka

# re: LINQ .First() method throws an error if there are no records!

Gravatar This is really helpful. I was not able to figure out the reason for the error.

Thanks a lot.... 7/30/2009 2:06 AM | biswa prakash

# re: LINQ .First() method throws an error if there are no records!

Gravatar Though you can use the Single extension method of LINQ it will throw an error if the collection contains more than one element. 12/14/2009 5:12 AM | http://www.intercasino.ws

# re: LINQ .First() method throws an error if there are no records!

Gravatar public Account GetAccountByUsername(string Username)
{
Account account = null;

using (VUForumDataContext dc = conn.GetContext())
{
account = (from a in dc.Accounts
where a.Username == Username
select a).FirstOrDefault();
}

return account;
}

In above code i still facing the error of "sequence contain no element" although i have replace the First() method with FirstOrDefault(). 3/17/2010 7:45 AM | cheeko

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Andrew Siemer - www.andrewsiemer.com