Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return one result from LINQ Query

Tags:

c#

linq

if you have a select LINQ query that should only return one result, do you have to have a foreach loop to get the result?

Or is there a better way?

like image 531
Tony The Lion Avatar asked Dec 18 '09 18:12

Tony The Lion


1 Answers

// Will return a default value if no object is found in the DB
db.Table.SingleOrDefault(x => x.something == someParameter);

or

// Will throw an exception if records are not found
db.Table.Single(x => x.something == someParameter);

Thanks to Mehrdad for the comment...both lines have been updated.

If it's possible that your query could result in more than one record being returned, then (as mentioned in comments) Single() and SingleOrDefault() are the wrong methods to call. You would keep the same syntax, but call First() and FirstOrDefault() respectively.

like image 188
Justin Niessner Avatar answered Sep 28 '22 18:09

Justin Niessner