c#使用linq反转和序列化字典

时间:2013-07-18 08:50:30

标签: c# linq

想知道是否可以在单个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 个答案:

答案 0 :(得分:2)

如果你这样做:

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

然后你得到:

  

1 - s

     

2 - s

     

3 - s

     

4 - m

     

5 - m

答案 1 :(得分: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);

答案 2 :(得分:1)

为此你可以使用SelectMany LINQ扩展方法:

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)));

答案 3 :(得分:1)

您可以使用SelectMany拆分值子列表,然后反转键和&amp;使用ToDictionary

将值转换为新词典
var result = original
    .SelectMany(k=> k.Value.Select(v => new { Key = v, Value = k.Key } ))
    .ToDictionary( t=> t.Key, t=> t.Value);