用sum对数据进行分组

时间:2009-02-12 09:40:05

标签: linq

我有以下列表:

 mat.Add(new Material() { ID = 1, ProdName = "Cylinder", Weight=23, Discontinued='N'  });
 mat.Add(new Material() { ID = 2, ProdName = "Gas", Weight = 25, Discontinued='N' });
mat.Add(new Material() { ID = 3, ProdName = "Match", Weight = 23, Discontinued='N' });

我想要一个结果:

2 Products have Weight 23 and Discontinued N
1 Product have Weigth 25 Discontinued N

3 个答案:

答案 0 :(得分:1)

目前尚不清楚你实际上在分组的是什么 - 重量是否已停止状态?如果是这样,你可以这样做:

var query = mat.GroupBy(material => 
                        new { material.Weight, material.Discontinued });

foreach (var result in query)
{
    Console.WriteLine("{0} products have {1}", result.Count(), result.Key);
}

答案 1 :(得分:0)

知道了!

.GroupBy(re => new { re.Weight, re.Discontinued })
           .Select(grp => new { CXXX = group.Key, Count = grp.Count()

答案 2 :(得分:0)

“只是”按重量分组并停止使用。

像这样的东西: var result = mat.GroupBy(a => new {a.Weight,a.Discontinued})。选择(b => new b.Key.Weight,b.Key.Discontinued,Count = b.Count()} );