2013-04-26 20 views
5

ho questa struttura:Linq GroupBy per passare dimensioni

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

e ho bisogno di trasformarlo a questa struttura:

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

Come posso usare LINQ per farlo? Uso GroupBy?

Grazie

risposta

6

Ti sicuramente bisogno di essere un qualcosa Dictionary<string, List<int>> o semplicemente simile? Userei SelectMany ad appiattirsi, e poi ToLookup:

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

Poi si può ancora usare come se si trattasse di un dizionario:

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

Si può fare questo:

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()); 
Problemi correlati