【问题标题】:Transform Dictionary<string, int> to Dictionary<int, List<string>>将 Dictionary<string, int> 转换为 Dictionary<int, List<string>>
【发布时间】:2018-08-28 12:24:45
【问题描述】:

Q我怎样才能最有效地转换Dictionary&lt;string, int&gt;to a Dictionary&lt;int, List&lt;string&gt;&gt;

示例

var input = new Dictionary<string, int>() { {"A", 1}, {"B", 1}, {"C", 2} ...
Dictionary<int, List<string>> result = Transform(input)
Assert.IsTrue(result, { {1, {"A", "B"}}, {2, {"C"}} ... });

【问题讨论】:

  • 你尝试了什么?那是作业吗?面试?
  • 你要使用的数据结构是:ILookup。 ;)

标签: c# linq dictionary


【解决方案1】:

按值对字典进行分组并将组键映射到键列表:

input.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(_ => _.Key).ToList())

【讨论】:

  • 这并不是 OP 所要求的。字典中每个项目的值将是 KeyValuePairList 而不仅仅是“A”、“B”等列表。也许你想要 input.GroupBy(x =&gt; x.Value).ToDictionary(x =&gt; x.Key, x =&gt; x.Select(z =&gt; z.Key).ToList());
  • @haim770 你是对的,需要添加一个选择,谢谢。
【解决方案2】:

这个怎么样?

var result = 
    dict.ToLookup(x => x.Value, x => x.Key)
    .ToDictionary(y => y.Key, y => y.ToList());

虽然我不明白为什么你不能只使用来自dict.ToLookup() 的结果而不将其更改为字典,例如:

var dict = new Dictionary<string, int>
{
    {"One", 1},
    {"Two", 2},
    {"1", 1},
    {"TWO", 2},
    {"ii", 2}
};

var test = dict.ToLookup(x => x.Value, x => x.Key);

Console.WriteLine(string.Join(", ", test[2])); // Prints: Two, TWO, ii

【讨论】:

    【解决方案3】:

    可以使用Linq来实现。

        private static Dictionary<int, List<string>> Transform(Dictionary<string, int> input)
        {
            var result = new Dictionary<int, List<string>>();
            foreach (var value in input.Select(x => x.Value).Distinct())
            {
                var lst = input.Where(x => x.Value == value).Select(x => x.Key).ToList();
                result.Add(value, lst);
            }
            return result;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多