Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.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# 获取数组上的foreach序列号_C#_Asp.net_Foreach - Fatal编程技术网

C# 获取数组上的foreach序列号

C# 获取数组上的foreach序列号,c#,asp.net,foreach,C#,Asp.net,Foreach,我有一个数组s[],我将其设置为: string [] s; s = data.Split(','); 使用foreach从s获取元素后: foreach (string c in s) { list.Items.Add(c); } 但我想把c的顺序写在c值附近,也就是说,它将显示在列表中: 0 hello 1 world 2 earth 我在

我有一个数组s[],我将其设置为:

    string [] s;
    s = data.Split(',');
使用foreach从s获取元素后:

foreach (string c in s)
                    {
                        list.Items.Add(c);  
                    }
但我想把c的顺序写在c值附近,也就是说,它将显示在列表中:

0 hello
1 world
2 earth

我在foreach中没有使用计数器,还有其他方法吗?

您必须使用计数器。您可以在foreach中使用一个,或者使用
for
循环并使用其计数器

编辑:如果你从一个空列表开始,你可以使用循环中的
list.Items.Count
来打印列表中当前的项目计数,尽管这不是一个好方法

// ugly
foreach (string c in s)
{
    list.Items.Add(list.Items.Count + " " + c);  
}

你得用柜台。您可以在foreach中使用一个,或者使用
for
循环并使用其计数器

编辑:如果你从一个空列表开始,你可以使用循环中的
list.Items.Count
来打印列表中当前的项目计数,尽管这不是一个好方法

// ugly
foreach (string c in s)
{
    list.Items.Add(list.Items.Count + " " + c);  
}

不,对于给定的代码,没有其他方法

您可以这样做:

 string [] s= {"0 Hello","1 World", "2 earth"};
 //your simple foreach loop
int counter=0;
foreach (string c in s)
{
    list.Items.Add(counter++ + " " + c);  
}
或者你这样做:

 string [] s= {"0 Hello","1 World", "2 earth"};
 //your simple foreach loop
int counter=0;
foreach (string c in s)
{
    list.Items.Add(counter++ + " " + c);  
}
或者更改代码,使用for循环

foreach (int i=0;i<s.Length;i++)
{
    list.Items.Add(i + " " + c[i]);  
}

foreach(inti=0;ino)对于给定的代码,没有其他方法

您可以这样做:

 string [] s= {"0 Hello","1 World", "2 earth"};
 //your simple foreach loop
int counter=0;
foreach (string c in s)
{
    list.Items.Add(counter++ + " " + c);  
}
或者你这样做:

 string [] s= {"0 Hello","1 World", "2 earth"};
 //your simple foreach loop
int counter=0;
foreach (string c in s)
{
    list.Items.Add(counter++ + " " + c);  
}
或者更改代码,使用for循环

foreach (int i=0;i<s.Length;i++)
{
    list.Items.Add(i + " " + c[i]);  
}

foreach(inti=0;i显而易见的是使用一个常规循环:

for (int i = 0; i < c.Length; i++) {
  list.Items.Add(i.ToString() + " " + c[i]);
}

显而易见的是使用常规循环:

for (int i = 0; i < c.Length; i++) {
  list.Items.Add(i.ToString() + " " + c[i]);
}

是否要在集合中显示其索引?是否要在集合中显示其索引?谢谢。但我不会使用计数器谢谢。但我不会使用计数器