我有重复值的字典。如何将这些重复的值合并为一个值 示例:
Accord - first
Accord.s - first
我想看到类似的东西:
Accord, Accord.s - first
答案 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}"));