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 your 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.