1

假设我有一组小数的字符串键,如下所示:

{ "Alfred", [1, 2] }
{ "Batman", [1, 2, 3] }

如何在 C# 中轻松地将这种关系反转到集合所在的位置:

{ 1, ["Alfred", "Batman"] }
{ 2, ["Alfred", "Batman"] }
{ 3, ["Batman" ] }
4

1 回答 1

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):前者选择的键,而后者选择原始字典的键。

于 2012-07-22T18:57:54.567 回答