我正在循环查看元素列表,并且想要为每个元素驻留在集合中的哪个位置分配一个数字以用于删除puposes。我的代码如下,只是给了我数量,有没有另外的选择来实现这一点。防爆。正确的方法将数字分配给列表集合中的元素
0猫 1狗 2鱼
等..
foreach (string x in localList)
{
{
Console.WriteLine(localList.Count + " " + x);
}
}
我正在循环查看元素列表,并且想要为每个元素驻留在集合中的哪个位置分配一个数字以用于删除puposes。我的代码如下,只是给了我数量,有没有另外的选择来实现这一点。防爆。正确的方法将数字分配给列表集合中的元素
0猫 1狗 2鱼
等..
foreach (string x in localList)
{
{
Console.WriteLine(localList.Count + " " + x);
}
}
,你必须使用一个for循环或使用单独的索引:
for(int i = 0; i < localList.Count;i++)
{
Console.WriteLine(i + " " + localList[i]);
}
是老学校,并返回到一个标准的for循环:
for(int i = 0; i < localList.Count; ++i)
{
string x = localList[i];
// i is the index of x
Console.WriteLine(i + " " + x);
}
LOL @一个for循环是“旧学校” – 2011-04-19 19:09:59
根据集合类型使用的是你可以使用类似
foreach (string x in locallist)
{
Console.WriteLine(locallist.IndexOf(x) + " " + x);
}
regds,佩里
如果你真的想要漂亮的,你可以使用LINQ
foreach (var item in localList.Select((s, i) => new { Animal = s, Index = i }))
{
Console.WriteLine(item.Index + " " + item.Animal);
}
谢谢你完全工作,我早些时候尝试过,但没有使用localList上的.Count。 – jpavlov 2011-04-19 19:13:18