2012-12-29 213 views
1

我有一個Dictionary<string, List<string>>類型的字典,我想將其轉換爲類型列表List<Dictionary<string, string>>。對於例如將列表字典轉換爲字典列表

輸入:

Key    List 
{ id, { "1",  "2", "3" }}, 
{ mkt, { "in", "uk", "us" }}, 
{ dept, { "sales", "test", "var" }}, 

輸出:

{ 
    { (id, "1"), (mkt , "in"), (dept, "sales") }, //1st Node as Dictionary 
    { (id, "1"), (mkt , "in"), (dept, "test") }, //2nd Node 
    { (id, "1"), (mkt , "in"), (dept, "var") }, 
    . 
    . //All possible combinations id, mkt and dept 
    . 
} 

我能夠使用循環來做到這一點,但我一直在尋找一個更清潔的方式可能使用一些C#特定的功能就像LINQ等等。

int a = 0; 
int NoOfTimesToRepeatAnElement = 1, NoOfTimesToRepeatList = count; 
int prevListSize = 1, currListSize = 1; 
foreach (var arg in dictionary) 
{ 
    a = 0; 
    prevListSize = currListSize; 
    currListSize = arg.Value.Count(); 

    NoOfTimesToRepeatAnElement = NoOfTimesToRepeatAnElement * prevListSize; 
    NoOfTimesToRepeatList = NoOfTimesToRepeatList/currListSize; 

    var list = arg.Value; 

    for (int x = 0; x < NoOfTimesToRepeatList; x++) 
    { 
     for (int y = 0; y < currListSize; y++) 
     { 
      for (int z = 0; z < NoOfTimesToRepeatAnElement; z++) 
      { 
       finalList[a++].Add(arg.Key, list[y]); 
      } 
     } 
    } 
} 

PS:我是在C背景和新的C#

回答

0
var list = dict.Select(kv => kv.Value.Select(v => new { kv.Key, Value = v })) 
       .CartesianProduct() 
       .Select(x => x.ToDictionary(y=>y.Key,y=>y.Value)) 
       .ToList(); 

public static partial class MyExtensions 
{ 
    //http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx 
    public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
    { 
     // base case: 
     IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() }; 
     foreach (var sequence in sequences) 
     { 
      var s = sequence; // don't close over the loop variable 
      // recursive case: use SelectMany to build the new product out of the old one 
      result = 
       from seq in result 
       from item in s 
       select seq.Concat(new[] { item }); 
     } 
     return result; 
    } 
} 
+0

有一個在你的解決方案,它不是給所有可能的組合的一些問題。 –

+0

對於給定的例子,它將給出三個組合,即'{(id,「1」),(mkt,「in」),(dept,「sales」)}','{(id,「2」 (mkt,「uk」),(dept,「test」)}和'{(id,「3」),(mkt,「us」),(dept,「var」)}'。理想情況下有27種可能的組合。 –

+0

@RaviGupta我更新了答案... –