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#
有一个在你的解决方案,它不是给所有可能的组合的一些问题。 –
对于给定的例子,它将给出三个组合,即'{(id,“1”),(mkt,“in”),(dept,“sales”)}','{(id,“2” (mkt,“uk”),(dept,“test”)}和'{(id,“3”),(mkt,“us”),(dept,“var”)}'。理想情况下有27种可能的组合。 –
@RaviGupta我更新了答案... –