基本上,我想在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循环。
当异常被抛出时,我使用的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);
}
}
提前感谢。