2

想知道是否可以在单个 LINQ 语句中反转字典?

结构如下;

Dictionary<string, List<string>> original = new Dictionary<string, List<string>>() 
    {
        {"s", new List<string>() { "1", "2", "3" }},
        {"m", new List<string>() { "4", "5", "6" }},
        {"l", new List<string>() { "7", "8", "9" }},
        {"xl", new List<string>() { "10", "11", "12" }},
    };

我想将其转换为类型的字典;

Dictionary<string, string> Reverse = new Dictionary<string, string>()
    {
        {"1", "s"},
        {"2", "s"}, //and so on
    };
4

4 回答 4

2

如果你这样做:

var reversed = original.SelectMany(x => x.Value.Select(y => new KeyValuePair<string, string>(y, x.Key)));

然后你得到:

1 - 秒

2 - 秒

3 - 秒

4 - 米

5 - 米

等等

于 2013-07-18T08:54:13.837 回答
2

就像是:

var result = (from kvp in original
              from value in kvp.Value
              select new {Key = value, Value = kvp.Key}).ToDictionary(a => a.Key, a => a.Value);

或者,如果您更喜欢方法语法:

var result = original.SelectMany(kvp => kvp.Value.Select(v => new {Key = v, Value = kvp.Key}))
                     .ToDictionary(a => a.Key, a => a.Value);
于 2013-07-18T08:54:24.887 回答
1

为此,您可以使用SelectManyLINQ 扩展方法:

var original = new Dictionary<string, List<string>>
                   {
                       { "s", new List<string> { "1", "2", "3" } },
                       { "m", new List<string> { "4", "5", "6" } },
                       { "l", new List<string> { "7", "8", "9" } },
                       { "xl", new List<string> { "10", "11", "12" } },
                   };

var keyValuePairs = original.SelectMany(o => o.Value.Select(v => new KeyValuePair<string, string>(v, o.Key)));
于 2013-07-18T08:58:03.683 回答
1

您可以使用 aSelectMany拆分值子列表,然后使用将键和值反转为新字典ToDictionary

var result = original
    .SelectMany(k=> k.Value.Select(v => new { Key = v, Value = k.Key } ))
    .ToDictionary( t=> t.Key, t=> t.Value);
于 2013-07-18T08:58:51.203 回答