c# - 双重分组为 Dictionary<int, Dictionary<string, List<Model>>>()

标签 c# linq group-by

我希望这可以通过 LINQ 解决,无需任何额外操作。

对于输入,我有一个模型列表:

public class Model 
{
  public int A { get; set; }
  public string B { get; set; }
  public int C { get; set; }
}

关于我应该得到的结果

Dictionary<int, Dictionary<string, List<Model>>>();

我试过下一个例子:

 var r = (from t in list
                    group t by new {t.A, t.B}
                    into grp
                    select new
                    {
                        grp.Key.A,
                        grp.Key.B,
                        Q = grp
                    }).ToList();

但它给我的不是我预期的,有什么办法可以解决这个问题吗?

最佳答案

鉴于您有一个 List 类型的列表,您可以使用:

var list = new List<Model>();

var lookup = list.GroupBy(model => new { A = model.A, B = model.B }).GroupBy(grp => grp.Key.A).ToDictionary(grp => grp.Key, grp => grp.ToDictionary(subgrp => subgrp.Key.B, subgrp => subgrp.ToList()));

你会看到变量lookup有您正在寻找的类型。

工作原理:

通过第一个 GroupBy,您正在创建一个 IGrouping,它具有匿名键类型,其成员为 int A 和 string B。这是因为:

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

这是对 question 的回答几年前我问过,如果你愿意,你可以检查它和@xanatos 的优秀答案。

关于c# - 双重分组为 Dictionary<int, Dictionary<string, List<Model>>>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68566315/

相关文章:

c# - GetCustomAttributes 不返回值

c# - Actor 后的对象类型?

c# - 单元测试 - 基于算法还是基于样本?

c# - 带Where 子句的Linq 左连接

c# - 有效地加入内存列表

c# - 使用 LINQ 和委托(delegate)执行递归函数

c# - 有任何理由抛出 DivideByZeroException 吗?

MySQL 正在复制其中一行中的 GROUP_CONCAT 内容

mysql - 分组依据和排序依据,每组有限制

php - MySQL查询排序/分组性能