Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 每个循环C的数组索引_C#_Visual Studio - Fatal编程技术网

C# 每个循环C的数组索引

C# 每个循环C的数组索引,c#,visual-studio,C#,Visual Studio,在C中,下面的For循环的For-each循环代码是什么?无法显示索引位置。谢谢你的帮助,我们将不胜感激 int[] n=new int[5]; n[0] = 12; n[1] = 24; n[2] = 36; n[3] = 48; n[4] = 60; //n[5]=2; // will display out of bounds error for (int i = 0; i

在C中,下面的For循环的For-each循环代码是什么?无法显示索引位置。谢谢你的帮助,我们将不胜感激

 int[] n=new int[5];
        n[0] = 12;
        n[1] = 24;
        n[2] = 36;
        n[3] = 48;
        n[4] = 60;

         //n[5]=2; // will display out of bounds error
        for (int i = 0; i < n.Length; i++)
        {
            Console.WriteLine("Aray position "+ i.ToString() + " & the value is " + n[i].ToString());
        }
foreach循环取决于内容,在您的情况下,如果需要当前索引,最好的选择是使用for循环


解释:foreach循环使用可枚举及其枚举数。在枚举数中有Current属性和MoveNext方法。因此,索引不属于…

您可以使用Select linq方法的重写来获取项目和索引

但正如你所看到的,这个方法并不短

     foreach (int i in n)
        {Console.WriteLine("Aray position " + Array.IndexOf(n,i) + " & the value is " + i);
        }

谢谢,这很有效

这是一个简短的版本

int[] n = { 12, 24, 36, 48, 60 };

foreach (var item in n.Select((x, i) => new { x, i }))
{
    Console.WriteLine("Aray position {0} & the value is {1}" , item.i, item.x);
}

Foreach没有索引,您可以创建自己的i并增加它,如果您需要索引,那么Foreach已经是一条路了-Foreach hereint a=0没有任何好处;n{Console.WriteLineAray position+a+&值为+i;a++;}中的foreach int i我编写了上面的代码。但是想要某种方法将a保留在内部。这样,a的范围就会变小。谢谢,我找到了数组。IndexOfn,我找到了方法。它在循环内部工作。这仅在n仅包含不同值时才起作用
     foreach (int i in n)
        {Console.WriteLine("Aray position " + Array.IndexOf(n,i) + " & the value is " + i);
        }
int[] n = { 12, 24, 36, 48, 60 };

foreach (var item in n.Select((x, i) => new { x, i }))
{
    Console.WriteLine("Aray position {0} & the value is {1}" , item.i, item.x);
}