2013-04-26 17 views
5

mam tę strukturę:LINQ GroupBy przełączyć wymiary

 var data1 = new Dictionary<int, List<string>> 
      { 
       { 1, new List<string> { "A", "B", "C" } }, 
       { 2, new List<string> { "B", "C" } } 
      }; 

i muszę przekształcić go do tej struktury:

 var data2 = new Dictionary<string, List<int>> 
      { 
       { "A", new List<int> { 1 } }, 
       { "B", new List<int> { 1, 2 } }, 
       { "C", new List<int> { 1, 2 } } 
      }; 

Jak mogę używać LINQ to zrobić? Czy używam GroupBy?

Dzięki

Odpowiedz

6

Czy zdecydowanie muszą to być Dictionary<string, List<int>> lub po prostu coś podobnego? użyłbym SelectMany spłaszczyć, a następnie ToLookup:

var data2 = data1.SelectMany(pair => pair.Value, (p, v) => new { p.Key, Value = v }) 
       .ToLookup(x => x.Value, x => x.Key); 

Następnie można nadal używać go tak, jakby był słownikiem:

foreach (var x in data2["B"]) 
{ 
    Console.WriteLine(x); // Prints 1 then 2 
} 
2

Można to zrobić:

var data2 = 
    (from p in data1 
    from v in p.Value 
    group p by v) 
    .ToDictionary(g => g.Key, g => g.Select(x => x.Key).ToList());