proper way assign numer to elements in a List Collection
I am looping through a list of elements, and would like to assign a number to where each element resides in the Collection for deletion puposes. My code below, just gives me the count, is there another option to achieve this. Ex.
0 cat 1 dog 2 fish
ect..
foreach (string x in localList)
开发者_开发技巧{
{
Console.WriteLine( localList.Count + " " + x);
}
}
be old school and go back to a standard for loop:
for(int i = 0; i < localList.Count; ++i)
{
string x = localList[i];
// i is the index of x
Console.WriteLine(i + " " + x);
}
If you really want to get fancy, you can use LINQ
foreach (var item in localList.Select((s, i) => new { Animal = s, Index = i }))
{
Console.WriteLine(item.Index + " " + item.Animal);
}
you have to use a for loop or use a separate index:
for(int i = 0; i < localList.Count;i++)
{
Console.WriteLine( i + " " + localList[i]);
}
Depending on the collection type you are using you can use something like
foreach (string x in locallist)
{
Console.WriteLine(locallist.IndexOf(x) + " " + x);
}
regds, perry
精彩评论