将foreach语句动态追加到c#代码中
本文关键字:代码 追加 foreach 语句 动态 | 更新日期: 2023-09-27 18:28:21
我正忙于一个c#项目,我有一个List{1,2,3}。我想在List对象的元素之间形成所有可能的匹配。使用3个foreach循环将很容易做到这一点。
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
...
根据您的定义,我想您需要一个幂集。示例取自此处
public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
private void button1_Click_2(object sender, EventArgs e)
{
List<int> temp = new List<int>() { 1,2,3};
List<IEnumerable<int>> ab = GetPowerSet(temp).ToList();
Console.Write(string.Join(Environment.NewLine,
ab.Select(subset =>
string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}
输出:
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
}