【问题标题】:LINQ Query to create Dictionary of DictionariesLINQ 查询以创建字典字典
【发布时间】:2014-04-29 14:26:26
【问题描述】:

我有以下架构:

父键 |钥匙 |价值

   1       A      3
   1       B      5
   1       C      6
   2       A      4
   2       D      8

我收到的是IQueryable<MyObject>

MyObject {
    public int ParentKey{get;set;}
    public String Key{get;set;}
    public int Value{get;set;}
}

我想把它变成一个字典字典,其中 ParentKey 是父字典的键,key 是子字典的键。我目前正在循环执行此操作,但我想看看如何使用 LINQ 来完成。

我保证特定父键中的键始终是唯一的,因此无需担心或检查重复键。

如何编写一个 LINQ 查询,将这些数据转换为

Dictionary<int, Dictionary<string, int>>

【问题讨论】:

  • 你从什么类型开始?
  • @I3arnon 我编辑了我的帖子以反映数据

标签: c# linq dictionary


【解决方案1】:

您需要先将列表按ParentKey 分组:

list.GroupBy(l => l.ParentKey)
    .AsEnumerable()     // to shift from IQueryable to IEnumerable and hydrate the results
    .ToDictionary(g => g.Key, g => g.ToDictionary(gg => gg.Key, gg => gg.Value));

【讨论】:

  • 如果源是 IQueriable(如问题所示),您可能希望在 DB 级别执行第一个分组,然后在 ToDictionary 之前执行 AsEnumerable。和公元前-1。您的第二个 ToDictionary 调用将在重复键上失败
  • @AZ OP 明确表示无需担心或检查重复键
  • @AZ。它是一个 IQueryable,我想把这个查询变成一个 ToDictionaryAsync,但他的回答是有效的,因为我提到对于给定的父键,这些键保证是唯一的。
  • 我的错。 -1 删除。我仍然认为 ToDictionary 之前的 AsEnumerable 需要放在那里。
  • @AZ AsEnumerable() 已添加。
猜你喜欢
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多