May 19 2008

The LINQ .First() command throws an error if no data exists

I incorrectly assumed that this would return null or an empty record if no data was found, but instead it throws an exception!

Instead I should have used .FirstOrDefault() which returns a null value if no record was found.

tblKeyword keywordRow = 
    ageRanges.FirstOrDefault(a => a.Keyword == setWord) 
        as tblKeyword;

Which returns either a tblKeyword item or null.

Comments (View)
blog comments powered by Disqus

Please...

Leave a comment if this has helped or offended you.

StackOverflow Id