我有一个Linq to Objects问题
我们正在制造产品并尝试按月报告lossCodes,按聚合lossCode排序。
因此,源数据(如 List< myProduct> myProducts )将如下所示:
.lossDate / .lossCode
4/10/2012 / TooLarge
4/11/2012 / TooSmall
4/14/2012 / TooSmall
4/14/2012 / TooSmall
4/14/2012 / TooSmall
5/1/2012 / TooLarge
5/10/2012 / TooSmall
4/10/2012 / TooLarge
5/10/2012 / WrongColor
结果转换应如下所示:
| TooSmall | TooLarge | WrongColor
04-2102 | 4 | 2 | 0
05-2012 | 1 | 1 | 1
所以它是一个分组(月,lossCode)...加上'总计'损失的排序(所以TooSmall cnt = 5然后TooLarge cnt = 3然后WrongColor cnt = 1是我试图得到的排序顺序) - 但我遇到了最后的问题。
query = from prod in myProducts
group prod by new {Month = prod.lossDate.ToString("yyyy-MM"), prod.lossCode} into g
select new
{
g.Key.Month,
ReasonCode = g.Key.lossCode,
NumLosses = g.Count()
}
into resultSet
orderby resultSet.NumLosses descending
select resultSet;
此代码无可否认是错误的(orderby resultSet.NumLosses显然不正确)...但我不明白如何将子组计数求和以进行最终排序。由于结果集的一些其他用途,我宁愿不尝试将“总计”记录移植到结果集上(对于匿名类型,我不确定如何完成)。以前有人经历过这样的事吗?
THX!
答案 0 :(得分:1)
我假设你想按NumLosses
query = (from prod in myProducts
group prod by new {Month = prod.lossDate.ToString("yyyy-MM"), prod.lossCode} into g
select new
{
g.Key.Month,
ReasonCode = g.Key.lossCode,
NumLosses = g.Count()
}
).OrderByDescending(x => c.NumLosses)