【问题标题】:Turning a Dictionary<Guid,IList<String>> into Dictionary<string,IList<Guid>> With LINQ?使用 LINQ 将 Dictionary<Guid,IList<String>> 转换为 Dictionary<string,IList<Guid>>?
【发布时间】:2016-11-07 16:16:54
【问题描述】:

我有一个Dictionary&lt;Guid,IList&lt;string&gt;&gt;,它显示了一个实体可以拥有的所有名称。

我想转换它以查看映射到所有实体的所有名称。 所以:

[["FFF" => "a", "b"],
 ["EEE" => "a", "c"]] 

变成

[["a" => "FFF", "EEE"],
 ["b" => "FFF"],
 ["c" => "EEE"]]

我知道使用 foreaches 很容易做到这一点,但我想知道是否有使用 LINQ/ToDictionary 的方法?

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:
    private static void Main(string[] args)
    {
        var source = new Dictionary<Guid, IList<string>>
        {
            { Guid.NewGuid(), new List<string> { "a", "b" } },
            { Guid.NewGuid(), new List<string> { "b", "c" } },
        };
    
        var result = source
            .SelectMany(x => x.Value, (x, y) => new { Key = y, Value = x.Key })
            .GroupBy(x => x.Key)
            .ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());
    
        foreach (var item in result)
        {
            Console.WriteLine($"Key: {item.Key}, Values: {string.Join(", ", item.Value)}");
        }
    }
    

    【讨论】:

      【解决方案2】:
      var dic = new Dictionary<string, List<string>>()
      {
          {"FFF", new List<string>(){"a", "b"}},
          {"EEE", new List<string>(){"a", "c"}}
      };
      
      var res = dic.SelectMany(x => x.Value, (x,y) => new{Key = y, Value = x.Key})
                   .ToLookup(x => x.Key, x => x.Value);
      

      【讨论】:

        【解决方案3】:
        Dictionary<int,IList<string>> d = new Dictionary<int ,IList<string>>(){
        {1,new string[]{"a","b"}},
        {2,new string[]{"a","d"}},
        {3,new string[]{"b","c"}},
        {4,new string[]{"x","y"}}};
        
        d.SelectMany(kvp => kvp.Value.Select(element => new { kvp.Key, element}))
         .GroupBy(g => g.element, g => g.Key)
         .ToDictionary(g => g.Key, g => g.ToList());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-01
          • 2014-10-22
          • 1970-01-01
          相关资源
          最近更新 更多