我在摆弄 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");
}