Reputation: 7702
I have the following class:
internal class ModuleScrap
{
public System.DateTime ReadTime { get; set; }
public string ScrapReason { get; set; }
public Int16 NetScrap { get; set; }
}
I could use some help with a LINQ query that retrieves all rows between a range of dates (that's the easy part), groups on ScrapReason
and determines the sum of NetScrap
for each group. I don't have much experience with grouping in LINQ.
Upvotes: 0
Views: 99
Reputation: 1500525
Something like this, I suspect:
var query = from scrap in scraps
where scrap.ReadTime >= minDate && scrap.ReadTime <= maxDate
group scrap by scrap.ScrapReason into g
select new { Reason = g.Key, Total = g.Sum(x => (int) x.NetScrap) };
Note that the int
cast is because Sum
isn't defined for Int16
values. An alternative is to change the grouping:
var query = from scrap in scraps
where scrap.ReadTime >= minDate && scrap.ReadTime <= maxDate
group (int) scrap.NetScrap by scrap.ScrapReason into g
select new { Reason = g.Key, Total = g.Sum() };
They'll give the same results - it's just a matter of which you prefer.
Upvotes: 7