将foreach语句动态附加到c#代码
我在忙一个c#项目,我有一个列表{1,2,3}。我想在List对象的元素之间形成所有可能的匹配。使用3个foreach循环很容易做到这一点将foreach语句动态附加到c#代码,c#,foreach,C#,Foreach,我在忙一个c#项目,我有一个列表{1,2,3}。我想在List对象的元素之间形成所有可能的匹配。使用3个foreach循环很容易做到这一点 foreach(int one in list) { foreach(int two in list) { foreach(int three in list) { // ... }}} 但是如果我不知道列表对象中的元素数量:如何使用
foreach(int one in list)
{
foreach(int two in list)
{
foreach(int three in list)
{
// ...
}}}
但是如果我不知道列表对象中的元素数量:如何使用foreach循环进行所有匹配?因此,如果列表中有6个元素,那么应该有6个基本foreach循环。。。
(我不想使用if语句,因为它占用了太多的空间)
如果使用foreach循环,如何动态更改foreach循环中使用的变量的名称?(你能说:
String "number"+i = new String("..."); //where i = number (int)
编辑:
输出应为:
1,1,1
1,2,1
1,2,2
1,2,3
1,3,1
1,3,2
1,3,3
...
根据你的定义,我想你需要一个电源
另一种方法是获取当前项目和其他项目,然后你也可以做你自己的事情
foreach (var one in ItemList)
{
var currentItem = one;
var otherItems = ItemList.Except(currentItem);
// Now you can do all sort off things
}
尝试递归我不能理解你的要求“形成所有可能的匹配”-你这是什么意思?你能举个例子吗?听起来有点像。举个例子来匹配列表中的元素。你想要笛卡尔积吗?是的,递归是你所需要的,当输出必须在一个输出行中包含所有3项时?(请参阅我对问题的编辑)Except是一个集合运算,执行一种不同的操作。1,1,1 Except 1不是1,1。
1
2
1,2
3
1,3
2,3
1,2,3
foreach (var one in ItemList)
{
var currentItem = one;
var otherItems = ItemList.Except(currentItem);
// Now you can do all sort off things
}