[英]Need help with LINQ query
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. 我可以在LINQ查询中使用一些帮助,该查询可检索日期范围(这是最简单的部分)之间的所有行,
ScrapReason
组并确定每个组的NetScrap
的总和。 I don't have much experience with grouping in LINQ. 我对LINQ分组没有太多经验。
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. 请注意,进行
int
强制转换是因为未为Int16
值定义Sum
。 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. 他们会给出相同的结果-这只是您喜欢的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.