gpt4 book ai didi

c# - Linq 中的多重嵌套分组

转载 作者:行者123 更新时间:2023-11-30 13:55:12 24 4
gpt4 key购买 nike

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

public class MyClass
{
public string GroupName;
public DateTime Dt;
.... other properties ....
}

假设我有以下 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

我希望从此列表中获取所有数据:

  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));

我知道这是错误的,但这是我唯一能想到的。我怎样才能得到我要找的东西?

最佳答案

使用选择:

return MyList
.GroupBy(d => d.Dt)
.Select(grp => grp.GroupBy(d => d.GroupName));

要准确获得您想要的内容,您需要在 Select 之后添加一个额外的 GroupBy:

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);

enter image description here

关于c# - Linq 中的多重嵌套分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com