score:3

var x = (from y in db.table
         where y.member_id == 1
         select new { y.member_id }).FirstOrDefault();

It'll return null if the user didn't exist.

You'll likely want to get rid of the new { } part though, if y.member_id is supposed to be a string.

var x = (from y in db.table
         where y.member_id == 1
         select y.member_id).FirstOrDefault();

score:0

You may use :

string m = db.table.where(member=>member.member_id == 1).FirstOrDefault().member_id.ToString();

, provided 'table' is a POCO or it can support property access.

score:0

You can use take 1 to limit the number of returned elements to one, but still you'll get a collection back from the query (of which you'd have to extract the first element using e.g. .First()).

But why not just use

val element = db.table.First(x => x.member_id == 1);

to find the element that satisfies your predicate?

score:0

If you are sure that the statement should only return a single result, instead of using .First/.FirstOrDefault you should use .Single/.SingleOrDefault so that you are effectively asserting that there will be only a single result. If the query returns more than one item, that would then be an error situation. This might be useful.


Related Articles