gpt4 book ai didi

c# - 在 C# 中使用 foreach 循环时修改集合

转载 作者:太空狗 更新时间:2023-10-29 20:33:07 25 4
gpt4 key购买 nike

<分区>

基本上,我想在 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);
}
}

提前致谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com