我们说我有一个字符串到小数的密钥集合,如下所示:
{ "Alfred", [1, 2] }
{ "Batman", [1, 2, 3] }
如何在C#中轻松地将此关系转换为集合的位置:
{ 1, ["Alfred", "Batman"] }
{ 2, ["Alfred", "Batman"] }
{ 3, ["Batman" ] }
答案 0 :(得分:4)
您可以使用LINQ:
var d = new Dictionary<string,int[]>{
{"Alfred", new[] {1,2}}
, {"Batman", new[] {1,2,3}}
};
var res = d
.SelectMany(p=>p.Value.Select(v => new {p.Key, Value = v}))
.GroupBy(p => p.Value)
.ToDictionary(g => g.Key, g => g.Select(v => v.Key).ToArray());
foreach (var p in res)
Console.WriteLine("{0} = ({1})", p.Key, string.Join(", ", p.Value));
此代码生成此输出(ideone link):
1 = (Alfred, Batman)
2 = (Alfred, Batman)
3 = (Batman)
请注意g => g.Key
和g => g.Select(v => v.Key)
之间的区别:前者选择组的键,而后者选择原始词典的键