tags:

views:

47

answers:

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

this statement should return only one record. & i want to retrieve that value the statement returns in a string format.

like

string m = x;

how can i do that?!

+3  A: 
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();
Matti Virkkunen
A: 

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.

Siva Gopal
A: 

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?

Dario
A: 

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.

spender