我有一个类型的字典,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
.
}
我可以使用 for 循环来做到这一点,但我正在寻找一种更干净的方式,可能使用一些 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# 的新手