2013-04-26 29 views
5

我有這樣的結構:的LINQ的GroupBy切換尺寸

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

,我需要把它轉換成這種結構:

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

我如何使用LINQ到這樣做呢?我使用GroupBy嗎?

感謝

回答

6

肯定需要的是一個類似Dictionary<string, List<int>>或只是什麼?我會用SelectMany拉平,然後ToLookup

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

那麼你仍然可以使用它,就好像它是一個字典:

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

你可以這樣做:

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