I have a dictionary of type Dictionary<string, List<string>> and I want to convert it to a list of type List<Dictionary<string, string>>. For e.g.
Input:
Key List
{ id, { "1", "2", "3" }},
{ mkt, { "in", "uk", "us" }},
{ dept, { "sales", "test", "var" }},
Output:
{
{ (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
.
}
I am able to do it using for loops but I was looking for a more clean way maybe using some C# specific feature like LINQ etc.
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: I am from C background and new to C#
1 Answer