Linq中的多个嵌套分组

Joh*_*tos 3 c# linq nested group-by

例如,假设我的C#代码MyClass定义为:

public class MyClass
{
    public string GroupName;
    public DateTime Dt;
    .... other properties ....
}
Run Code Online (Sandbox Code Playgroud)

假设我有以下内容List<MyClass>(将其显示为表格,因为它似乎是描述内容的最简单方法):

GroupName:       Dt:             Val:
Group1           2016/01/01      a
Group1           2016/01/02      b
Group1           2016/01/03      c
Group2           2016/01/01      d
Group2           2016/01/02      e
Group3           2016/01/01      f
Group3           2016/01/02      g
Group3           2016/01/03      h
Run Code Online (Sandbox Code Playgroud)

而且我希望从这个列表中获取所有数据:

  1. 首先按分组 Dt
  2. 其次按分组 GroupName

所以,(我确定这是错的,但我希望它能解释我在寻找什么),我想得到一个 IEnumerable<IGrouping<DateTime, IEnumerable<IGrouping<string, IEnumerable<MyClass>>>>

我最好的尝试得到这个是以下:

return MyList
    .GroupBy(d => d.Dt)
    .GroupBy(grp => grp.ToList().GroupBy(d => d.GroupName));
Run Code Online (Sandbox Code Playgroud)

我知道这是错的,但这是我唯一能想到的.我怎么能得到我想要的东西?

Mar*_*zek 8

用途Select:

return MyList
    .GroupBy(d => d.Dt)
    .Select(grp => grp.GroupBy(d => d.GroupName));
Run Code Online (Sandbox Code Playgroud)

为了得到你想要的东西你需要额外GroupBySelect:

var groups = MyList
    .GroupBy(d => d.Dt)
    .Select(grp => new { key = grp.Key, items = grp.GroupBy(d => d.GroupName) })
    .GroupBy(grp => grp.key, grp => grp.items);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 它是一个嵌套组,但为了澄清这里是一个更明确的版本,你可以```到所有内容并看看发生了什么:return MyList .GroupBy(d => d.Dt).Select(g1 => new {Dt = g1.Key,Dts = g1.GroupBy(d => d.GroupName).Select(g2 => new {GroupName = g2.Key,GroupNames = g2})}); (2认同)