【问题标题】:convert Dictionary<int, Enumerable> to Dictionary<int, Enumerable> inverting content将 Dictionary<int, Enumerable> 转换为 Dictionary<int, Enumerable> 反转内容
【发布时间】:2009-08-24 21:38:21
【问题描述】:

为了清楚起见,假设我们有学生和班级,这是多对多的关系。

我有一个字典,其中键是学生 id,而 Enumerable 是一个类的集合(比如我们只有 id),我想将它恢复为一个包含 classId,students 的字典

有没有办法用 Linq 做到这一点?我可以想办法用循环来做到这一点,但我确信有办法做到这一点。

【问题讨论】:

    标签: c# .net linq dictionary


    【解决方案1】:
    var newDic = dic
       .SelectMany(pair => pair.Value
                               .Select(val => new { Key = val, Value = pair.Key }))
       .GroupBy(item => item.Key)
       .ToDictionary(gr => gr.Key, gr => gr.Select(item => item.Value));
    

    【讨论】:

    • 起初我以为你回答了自己的问题。伙计,我累了。
    【解决方案2】:

    应该这样做:

    var invertedDic = dic
        .SelectMany(x => x.Value, (pair, value) => new {key = pair.Key, value = value})
        .GroupBy(x => x.Value, x => x.Key, (value, key) => new {value, key})
        .ToDictionary(x => x.Value, x => x.Key);
    

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2011-03-05
      • 2010-10-17
      相关资源
      最近更新 更多