c#:如何调用多个'for循环'高效
本文关键字:for 高效 循环 何调用 调用 | 更新日期: 2023-09-27 18:13:10
使用c#作为我的语言,我需要创建多个for循环,利用数组和字符串。我甚至可能在我的代码中使用10个for循环,但我知道有一个更好的方法来运行多个for循环,而不用手动编写50个for循环,快捷方式可以是什么,
**我想完成的事情:
我想打印数组[]的一系列可能性,数组[]的所有可能性,例如:数组[0],数组[0],数组[1],数组[0],数组[1],数组[2]等等,我想要一个小程序打印数组中所有的组合
下面是我的低效代码:
string[] array = new string[] { "and", "nand", "not", "or", "nor", "xor" };
for (int i = 0; i < array.Length; i++)
{
string test = array[i];
Debug.WriteLine(array[i]);
}
for (int i = 0; i < array.Length; i++)
{
string test = array[i];
Debug.WriteLine(array[i]);
}
for (int i = 0; i < array.Length; i++)
{
string test = array[i];
Debug.WriteLine(array[i]);
}
我如何缩短这个,以便我运行x数量的'for循环'?在这种情况下,有3个for循环需要变成1个大的for循环?执行for循环x次
你的意思是:
for(int repeat=0; repeat<3; ++repeat)
for(int i=0; i<array.Length; ++i)
Debug.WriteLine(array[i]);
或者更好的是,没有笨拙的索引:
for(int repeat=0; repeat<3; ++repeat)
foreach(var line in array)
Debug.WriteLine(line);
使用嵌套for循环:
int n = 3; // how many times you want to run it for
for (int j = 0; j < n; j++) {
for (int i = 0; i < array.Length; i++)
{
string test = array[i];
Debug.WriteLine(array[i]);
}
}
为了进一步改进代码,您甚至不需要string test = array[i];
,您可以使用foreach
循环,如Blindy的答案
我想这就是你想要的。
string[] array = new string[] { "and", "nand", "not", "or", "nor", "xor" };
for (var i = 0; i < array.Length; i++)
{
for (var j = 0; j < i; j++)
{
Debug.Write(array[j]);
}
Debug.WriteLine();
}
这将打印:
and
and nand
and nand not
...
你问题中的代码写成
会更有效using System.Linq;
var strings = new[] { "and", "nand", "not", "or", "nor", "xor" };
foreach (var s in strings.Repeat(3).SelectMany(s => s))
{
Debug.WriteLine(s);
}
如果循环不相互作用,实际的执行顺序并不重要,如果活动足够复杂,你可以这样做,
var loops = Enumerable.Range(1, 3).Select(i =>
{
foreach (var s in strings)
{
Debug.WriteLine(s);
}
Task.FromResult(true);
});
Task.WhenAll(loops).Wait();
在你的帖子信息之后,这是你想要的代码
public void Strange(string[] array)
{
Debug.Assert(array.Length > 1);
for (var i = 1; i < array.Length; i++)
foreach (var item in array.Take(i))
Debug.WriteLine(item);
}
但是不能提供像array[0], array[2], array[3], etc.
(跳过array[1]
)这样的组合