Nubix
Nubix

Reputation: 21

how to return a value from a LINQ statement

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?!

Upvotes: 2

Views: 232

Answers (4)

spender
spender

Reputation: 120380

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.

Upvotes: 0

Dario
Dario

Reputation: 49208

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?

Upvotes: 0

Siva Gopal
Siva Gopal

Reputation: 3502

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.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

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();

Upvotes: 3

Related Questions