if you have a select LINQ query that should only return one result, do you have to have a foreach loop开发者_如何学C to get the result?
Or is there a better way?
// 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.
var myLinqObj = db.MyObjects.Take(1).SingleOrDefault();
You can use either First
or Single
.
First
returns the first row, whether there are multiple rows or just the one.
Single
expects only one row to be returned, and throws an exception if there are multiple rows.
Single
is therefore potentially a better choice if you expect to only have one row, so that you'll see the problem immediately and can troubleshoot it.
You can just use .First() or .FirstOrDefault() like so:
Foo foo = query.Select(a => a.Name == "foo").FirstOrDefault();
From all the have have said my addition is the use the Value
property after you have a single element if you are using LINQ-to-XML.
And the Select new { *cols* }
if it a list or array or table.
Example.
... select new {c.Name, c.Value};
This tip is to enable you get the values.
精彩评论