Question

I am struggling with a grouping linq query

I have this:

DateTime dateFrom = new Date(2014,8,2);
var GroupedPrices = Prices.Where(p => p.ArrivalDateFrom <= dateFrom
                    &&
                    p.ArrivalDateTo > dateFrom)
                    .GroupBy(p => p.ItemID);

I am trying to get to a single price of each ID - eg. in/from each group, based on the newest ValidFrom date of that price. I have started by grouping them by their ItemID's (not the individual price record id's) but am struggling in working out how to grab just a single one based on that newest ValidFrom date. I thought I could order them before grouping, but wasn't sure that would stick after the grouping was done.. ie

expecting it will use a Max(x=>x.ValidFrom) type thing or OrderByDescending(x=>x.ValidFrom).First() but cant work that out

any help much appreciated

thanks

Was it helpful?

Solution

I think you just need to select what you want, at the end, like so:

DateTime dateFrom = new Date(2014,8,2);
var GroupedPrices = Prices
    .Where(p => p.ArrivalDateFrom <= dateFrom && p.ArrivalDateTo > dateFrom)
    .GroupBy(p => p.ItemID)
    .Select(g => new{ ItemId = g.Key, NewestPrice = g.OrderByDescending(p => p.ValidFrom).First() });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top