1

我有一个 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 显然不正确)......但我不明白如何对子组 Counts 求和才能进行最终排序。由于结果集的一些其他用途,我宁愿不尝试将“总计”记录移植到结果集(并且对于匿名类型,我不确定如何完成)。以前有人经历过这样的事情吗?

谢谢!

4

1 回答 1

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)
于 2012-09-05T04:27:20.807 回答