C# 获取数组上的foreach序列号
我有一个数组s[],我将其设置为: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 我在
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]);
}
是否要在集合中显示其索引?是否要在集合中显示其索引?谢谢。但我不会使用计数器谢谢。但我不会使用计数器