C# 通过笛卡尔积从字典<string, IEnumerable<object>> 中获取 IEnumerable<Dictionary<string, object>>
C# get IEnumerable<Dictionary<string, object>> from Dictionary<string, IEnumerable<object>> by cartesian product
来自这本词典
var foo = new Dictionary<string, IEnumerable<object>>
{
{"key1", new object[] {1}},
{"key2", new[] {"one", "two"}},
{"key3", new[] {"three", "four"}}
}
我想得到这个 IEnumerable>
IEnumerable<Dictionary<string, object>> bar = {
{{"key1", 1}, {"key2", "one"}, {"key3", "three"}},
{{"key1", 1}, {"key2", "one"}, {"key3", "four"}},
{{"key1", 1}, {"key2", "two"}, {"key3", "three"}},
{{"key1", 1}, {"key2", "two"}, {"key3", "four"}}
}
简单来说,我需要 python itertools.product 函数 Cartesian product of a dictionary of lists.
的 C# 模拟
我已经阅读 Generating all Possible Combinations 但无法弄清楚我应该如何更改它并且我无法找到有关笛卡尔积与字典(带键)结果的解决方案。
提前致谢
快速解决方案是只对字典值进行笛卡尔乘积,同时保留有关键的信息,然后重新创建字典:
// [[("key1",1)],[("key2","one"),("key2,"two")],[("key3","three"),("key3","four")]]
var collectionsOfKeyValuePairs =
foo.Select(k => k.Value.Select(v => new KeyValuePair<string, object>(k.Key, v)));
// [[(key1,1),(key2,one),(key3,three)],
// [(key1,1),(key2,one),(key3,four)],...etc
var product = CartesianProduct(collectionsOfKeyValuePairs);
var dictionaries = product.Select(collection=> collection.ToDictionary(k=> k.Key, k=> k.Value));
来自这本词典
var foo = new Dictionary<string, IEnumerable<object>>
{
{"key1", new object[] {1}},
{"key2", new[] {"one", "two"}},
{"key3", new[] {"three", "four"}}
}
我想得到这个 IEnumerable
IEnumerable<Dictionary<string, object>> bar = {
{{"key1", 1}, {"key2", "one"}, {"key3", "three"}},
{{"key1", 1}, {"key2", "one"}, {"key3", "four"}},
{{"key1", 1}, {"key2", "two"}, {"key3", "three"}},
{{"key1", 1}, {"key2", "two"}, {"key3", "four"}}
}
简单来说,我需要 python itertools.product 函数 Cartesian product of a dictionary of lists.
的 C# 模拟我已经阅读 Generating all Possible Combinations 但无法弄清楚我应该如何更改它并且我无法找到有关笛卡尔积与字典(带键)结果的解决方案。
提前致谢
快速解决方案是只对字典值进行笛卡尔乘积,同时保留有关键的信息,然后重新创建字典:
// [[("key1",1)],[("key2","one"),("key2,"two")],[("key3","three"),("key3","four")]]
var collectionsOfKeyValuePairs =
foo.Select(k => k.Value.Select(v => new KeyValuePair<string, object>(k.Key, v)));
// [[(key1,1),(key2,one),(key3,three)],
// [(key1,1),(key2,one),(key3,four)],...etc
var product = CartesianProduct(collectionsOfKeyValuePairs);
var dictionaries = product.Select(collection=> collection.ToDictionary(k=> k.Key, k=> k.Value));