开发者

Lambda Expression to get 3 field values

I want to retrieve 3 fields from a row inside a LIST<> and at the moment I am doing it like this

FOS1 = (from res in sortedSearchResults
where Convert.ToInt32(res.tID) == tID
select res.FOS1).First();
FOS2 = (from res in sortedSearchResults
where Convert.ToInt32(res.tID) == tID
select res.FOS2).First();
FOS3 = (from res in sortedSearchResults
where Convert.ToInt32(res.tID) == tID
select res.FOS3).First();

This works fine, however I wish instead of 3 statements, I have only 1, but I am not very familiar with Lambda Expressions.

I tried the following:-

var name = sortedSearchResults.Where(i => Convert.ToInt32(i.tID) == tID)
.Select(i => new { FOS1 = i.FOS1, FOS2 = i.FOS2, FOS3 = i.FOS3 });

but FOS1, FOS2 and FOS3 are always blank, when there is supposed to be values in them. Can someone tell me what am I doing wrong, and why am I not getting the vars populated?

Thanks for you开发者_JAVA百科r help and time


Your select projection looks correct. The only thing I notice is that in the separate statements, you were calling .First where you aren't doing that in the combined query. Is it possible that you are returning more records than expected in the combined query and not iterating over them as much.

Also, realize that First is an eager loaded construct (forcing the load) whereas Select is a lazy evaluation. If your context goes out of scope before the iteration occurs, you will likely get an empty result set. This often happens if you wrap your object context in a Using block and the actual databinding iteration occurs outside of the scope of the using block. You may need to add .ToList() at the end of your combined query to force the load.


You need to force the evaluation, e.g.

var name = sortedSearchResults.Where(i => Convert.ToInt32(i.tID) == tID).Select(i => new {FOS1 = i.FOS1, FOS2 = i.FOS2, FOS3 = i.FOS3}).First();


As I understand, FOS1, FOS2 and FOS3 are three local variables which you want to fill with values.

You could try something like that:

sortedSearchResults.First(i => Convert.ToInt32(i.tID) == tID)
.Each(i =>  
{ 
FOS1 = i.FOS1;
FOS2 = i.FOS2; 
FOS3 = i.FOS3; 
});

Or, you could just select the object and fill the variables based on its properties.


I have managed to solve it and it was my bad. First of all I did .First() at the end of the statement, and then I had to call name.FOS1 and name.FOS2 and name.FOS3. Also the resultset will always contain 1 row since it is already filtered previously in the code, to get the sortedResults. Thanks for all the help! –

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜