首页 > 解决方案 > 使用 LINQ 反转和展平字典

问题描述

我有一些看起来像:

{
  "Item1": ["1a", "1b", "1c"],
  "Item2": ["2a"],
  "Item3": ["3a", "3b"]
}

我想要的是这样的:

{
  
  "1a": "Item1", 
  "1b": "Item1", 
  "1c": "Item1",
  "2a": "Item2",
  "3a": "Item3", 
  "3b": "Item3"
}

我已经能够做到这一点,但只是想知道是否有更简洁的 LINQ 方式?

Dictionary<string, string[]> items = new Dictionary<string, string[]>(...);
Dictionary<string, string> endResult = new Dictionary<string, string>(); // This is correct

var reversed = items.ToDictionary(x => x.Value, x => x.Key);

foreach (var item in reversed)
{
    foreach (var inner in item.Key)
    {
        endResult.Add(inner, item.Value);
    }
}

标签: c#linqdictionary

解决方案


Dictionary<string, string> endResult = items.Select(o => o.Value.Select(v => new { Value = v, Key = o.Key }))
                                            .SelectMany(o => o)
                                            .ToDictionary(o => o.Value, o => o.Key);

推荐阅读