基本上,我想在 foreach 循环内从列表中删除一个项目。我知道这在使用 for 循环时是可能的,但对于其他目的,我想知道这是否可以使用 foreach 循环来实现。
在python中,我们可以通过执行以下操作来实现:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in a:
print i
if i == 1:
a.pop(1)
这给出了以下输出
>>>1
3
4
5
6
7
8
9
但是当在 c# 中做类似的事情时,我得到一个 InvalidOperationException,我想知道是否有办法解决这个问题,而不仅仅是使用 for loop。
我在抛出异常时使用的 c# 中的代码:
static void Main(string[] args)
{
List<string> MyList = new List<string>(new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9"});
foreach (string Item in MyList)
{
if (MyList.IndexOf(Item) == 0)
{
MyList.RemoveAt(1);
}
Console.WriteLine(Item);
}
}
提前致谢