score:6

Accepted answer
var mylinqobj = db.myobjects.take(1).singleordefault();

score:0

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.

score:2

you can just use .first() or .firstordefault() like so:

foo foo = query.select(a => a.name == "foo").firstordefault();

score:5

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.

score:19

// 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.


Related Query