2011-04-19 28 views
1

我正在循环查看元素列表,并且想要为每个元素驻留在集合中的哪个位置分配一个数字以用于删除puposes。我的代码如下,只是给了我数量,有没有另外的选择来实现这一点。防爆。正确的方法将数字分配给列表集合中的元素

0猫 1狗 2鱼

等..

 foreach (string x in localList) 
     { 
      { 
       Console.WriteLine(localList.Count + " " + x); 
      } 
     } 

回答

1

,你必须使用一个for循环或使用单独的索引:

for(int i = 0; i < localList.Count;i++) 
{ 
    Console.WriteLine(i + " " + localList[i]); 
} 
+0

谢谢你完全工作,我早些时候尝试过,但没有使用localList上的.Count。 – jpavlov 2011-04-19 19:13:18

2

是老学校,并返回到一个标准的for循环:

for(int i = 0; i < localList.Count; ++i) 
{ 
    string x = localList[i]; 
    // i is the index of x 
    Console.WriteLine(i + " " + x); 
} 
+2

LOL @一个for循环是“旧学校” – 2011-04-19 19:09:59

1

根据集合类型使用的是你可以使用类似

foreach (string x in locallist) 
{ 
    Console.WriteLine(locallist.IndexOf(x) + " " + x); 
} 

regds,佩里

2

如果你真的想要漂亮的,你可以使用LINQ

foreach (var item in localList.Select((s, i) => new { Animal = s, Index = i })) 
{ 
    Console.WriteLine(item.Index + " " + item.Animal); 
} 
相关问题