Narrowing LINQ query to one column
I'm trying to setup a query like this. So at first I'm selecting complete objects..
var values = (from p in Products
where p.LockedSince == null
select p);
Then optionally I'm adding extra where
's
if(SupplierId > 0)
values = values.Where(p => p.SupplierId == SupplierId);
And in 开发者_如何学运维the end, I don't need the complete product objects anymore, I just need a simple distinct and ordered list of one column (p.LocationName
) .. something like this:
values = values.Select( p.LocationName ).Distinct().OrderBy(x => x);
I've tried something like Select(loc => new { p.LocationName })
, but with no luck.
If you don't need intermediate results more effective way would be to write single query
var values = (from p in Products
where (p.LockedSince == null && (SupplierId <=0 || p.SupplierId == SupplierId))
select p.LocationName).Distinct().OrderBy(x => x);
values = values.Select( p => p.LocationName ).Distinct().OrderBy(x => x);
精彩评论