有没有一种方法可以编码for循环,以便它不会在序列中递增?


10

我有这个循环:

  for (int i = 1; i < 10; i++)

但是相反,我只想让我的数字分别为1,2,4,5和7,我将对此进行硬编码。

有什么办法可以像数组一样做到这一点吗?


1
创建所需数字的数组并使用foreach
PaulF

2
请提供更多详细信息,以便我们可以帮助提供相关的解决方案?您计划多久跳过一次号码?您希望跳过多少个数字?您怎么知道要跳过哪些数字?为什么首先跳过数字?您如何以及如何对此进行硬编码?
Corentin Pane

这并不是我一开始就想找到重复副本所想的那么容易
蒙祝

Answers:


13

您可以使用数组来给出所需的数字

int[] loop = new int[] {1,2,4,5,7};
foreach(int i in loop)
    Console.WriteLine(i);

还是以内联方式执行,当我认为值列表增加时,这种方式不太干净

foreach(int i in new int[] {1,2,4,5,7})
    Console.WriteLine(i);

1
第二个对我来说更干净-数组仅在循环期间处于作用域内。另外,要使其真正“干净”,您可以删除int声明,因为编译器将从内容中确定该声明。
Rufus L


4

基本上,这里的答案是正确的,只是因为您明确要求a for而不是foreach循环:

int[] loop = new int[] { 1, 2, 4, 5, 7 };
for (int i = 0; i< loop.Length; i++)
{
    Console.WriteLine(loop[i]);
}

https://dotnetfiddle.net/c5yjPe


0

如果您特别想要for循环,请执行以下操作:

var list = new List<int>() { 1, 2, 4, 5, 7 };
        for (int i = 0; i < list.Count; i++) // Loop through List with for
        {
            Console.WriteLine(list[i]);
        }

0

显然,对于一般情况,正确的答案是使用foreach或索引查找(如其他答案所示),但仅出于完整性考虑:

您可以在表达式中使用任何语句for,包括条件语句。考虑到这一点,很容易为所需集合建立条件增量甚至是穷举的条件(状态机?):

for (int i = 1; i <= 7; i += (i == 5 || i == 2) ? 2 : 1)
{
    Console.Write(i);
}
// Output: 12457

for (int i = 1; i > 0; i = i switch {1=>2, 2=>4, 4=>5, 5=>7, 7=>-1})
{
    Console.Write(i);
}
// Output: 12457

甚至是像自动索引查找这样的愚蠢的东西:

for (int i = 1; i > 0; i = new []{0,2,4,0,5,7,0,-1}[i])
{
    Console.Write(i);
}
// Output: 12457
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.