对每个组内参数的出现进行分组和计数

时间:2012-05-09 15:14:50

标签: linq sqlite group-by linqpad

我正在摆弄LINQPad,我确信这个问题已经被问到了,但我一直在努力寻找相当长的一段时间。

我有一个这样的集合:

Age  Material
---  --------
3    Steel
3    Steel
3    PVC
4    Steel
4    PVC

我想首先按材质对其进行分组,然后计算每个材质组中每个年龄的出现次数,结果如下:

{Mat = Steel,
   [(Age = 3, Count = 2),
    (Age = 4, Count = 1)]}
{Mat = PVC,
   [(Age = 3, Count = 1),
    (Age = 4, Count = 1)]}

我知道这与嵌套组有关,但我无法做到正确。我一直在尝试这样的东西(只有没有问号),但我不知道如何到达每组中的项目:

var matGroups = from line in Pipelines                              
                group line by line.Material into matGroup
                from ???? in ???
                group ???? by ???.Age;

如果相关,我正在查询的数据存储在SQLite中。

更新

以下代码获取了我想要的数据。但是,如果可能的话,我仍然想知道在单个查询中执行此操作的正确方法。

var materials = from p in Pipelines
                group p by p.Material into matGroup
                select matGroup.Key;

foreach (string material in materials)
{
    var ages = from p in Pipelines
               where p.Material == material
               group p by p.Age into ageGroup
               select new {Age = ageGroup.Key, Count = ageGroup.Count()};

    ages.Dump(material + " Pipelines");
}

1 个答案:

答案 0 :(得分:1)

这只是AgeMaterial的分组:

from p in Pipelines
group p by new { p.Material, p.Age } into g
orderby g.Key.Material, g.Key.Age
select new { g.Key.Material, g.Key.Age, Count = g.Count () }