开发者

how to return a value from a LINQ statement

开发者 https://www.devze.com 2023-01-16 14:27 出处:网络
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 form
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?!


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


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消