2011-04-19 30 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); 
} 
相關問題