2012-12-29 3 views
1

나는 Dictionary<string, List<string>> 유형의 사전을 가지고 있으며 형식을 List<Dictionary<string, string>>으로 변환하고 싶습니다. 예 :사전 목록을 사전 목록으로 변환

입력 :

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

출력 : 내가 루프를 사용하여 할 수 있어요하지만 난 아마 등 LINQ와 같은 일부 C#을 특정 기능을 사용하여 더 깨끗한 방법을 찾고 있었다

{ 
    { (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 
    . 
} 

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 답변을 업데이트했습니다 ... –

관련 문제