在 LINQ 中生成 n 个集合的排列
我有一个 IEnumerable 数组 (IEnumerable[]),希望生成这些 IEnumerable 中元素的所有可能组合。 它与此问题类似:使用 LINQ 生成排列 但我不知道我事先会有多少个 IEnumerable,因此无法使用所描述的 LINQ 语句。
举个例子: 我的数组
IEnumerable[] array;
例如,
array[0]={0,1,2};
array[1]={a,b};
具有这些元素然后我希望返回这些元素:
{{0,a},{0,b},{1,a},{1,b},{2,a},{2,b}}
但它也可能包含:
array[0]={0,1,2};
array[1]={a,b};
array[2]={w,x,y,z};
然后我需要适当的排列。我没有关于有多少 IEnumerable 的任何信息,也没有关于每个 IEnumerable 拥有多少元素的信息。
预先感谢您的帮助,
拉斯
I have an array of IEnumerable (IEnumerable[]) and would like to generate all possible combinations of the elements in these IEnumerables.
It is similar to this problem: Generating Permutations using LINQ
but I do not know how many IEnumerables I will have beforehand and thus cannot use the described LINQ statement.
To give an example:
My array
IEnumerable[] array;
has for example these elements
array[0]={0,1,2};
array[1]={a,b};
Then I would like these to be returned:
{{0,a},{0,b},{1,a},{1,b},{2,a},{2,b}}
But it might also hold:
array[0]={0,1,2};
array[1]={a,b};
array[2]={w,x,y,z};
Then I would need the appropriate permutations. I do not have any information on how many IEnumerables and no information on how many elements each IEnumerable holds.
Thanks in advance for any help,
Lars
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您想要笛卡尔积。这应该可行,尽管我没有特别仔细地观察边缘情况
Seems like you want the Cartesian_product. This should work, although I didn't look particularly carefully at edge-cases
尝试将此作为方向(我确定您需要修改,而且我还没有编译它,因此可能存在一些语法错误)
同样,未编译,但它应该是什么要做的就是继续将“item1, item2”添加到列表中,其中 item1 = 旧的“item1, item2”,item2 = 只是第 n 个数组中的新条目。
因此,字符串数组 [a, b, c] + 字符串数组 [1, 2, 3, 4] 应该产生:
{a, 1}, {a, 2}, {a, 3}, {a, 4 }, {b, 1}...
并将字符串数组 [x, y, z] 添加到第一个 to 将产生:{a, 1, x}, {a, 1, y }、{a, 1, z}
等等。Try this as a direction (you'll need to modify, I'm sure, and I haven't compiled it, so there may be some syntax errors)
Again, not compiled, but what it should do is keep adding "item1, item2" to a list with a where item1 = the old "item1, item2" and item2 = just the new entry from the nth array.
Thus string array [a, b, c] + string array [1, 2, 3, 4] should yield:
{a, 1}, {a, 2}, {a, 3}, {a, 4}, {b, 1}...
and adding string array [x, y, z] to the first to would then yield:{a, 1, x}, {a, 1, y}, {a, 1, z}
and so forth.