如何将字典中的重复值合并为一个值

时间:2019-06-11 09:46:03

标签: c# dictionary

我有重复值的字典。如何将这些重复的值合并为一个值 示例:

 Accord - first
 Accord.s - first

我想看到类似的东西:

 Accord, Accord.s - first

1 个答案:

答案 0 :(得分:3)

如果我没听错,您有字典

Dictionary<string, string> source = new Dictionary<string, string>() {
  {"Accord", "first"},
  {"Accord.s", "first"},
  {"Gamma", "second"}, 
};

,您想按Value 分组,可以在 Linq 的帮助下完成:

 using System.Linq;

 ...

 // If you want to create a dictionary:
 Dictionary<string, string> result = source
   .GroupBy(pair => pair.Value)
   .ToDictionary(
      chunk => string.Join(", ", chunk.Select(pair => pair.Key)),
      chunk => chunk.Key);

 string report = string.Join(Environment.NewLine, result
   .Select(pair => $"{pair.Key} : {pair.Value}"));

 Console.Write(report);

结果:

Accord, Accord.s : first
Gamma : second

如果您只想查询(而不是字典)

var result = source
   .GroupBy(pair => pair.Value)
   .Select(chunk => new {
      Key   = string.Join(", ", chunk.Select(pair => pair.Key)),
      Value = chunk.Key});

// and then
string report = string.Join(Environment.NewLine, result
   .Select(pair => $"{pair.Key} : {pair.Value}"));