gpt4 book ai didi

C# list.remove 在 foreach 循环中抛出枚举操作错误

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:19 26 4
gpt4 key购买 nike

我查看了多个与我相关的 SO 问题以及谷歌搜索,但我一直无法找到适合我的解决方案。

给定一个文件列表,出于某种原因,我试图剔除所有非 CS 文件。我获取字符串数组,转换为列表,并遍历列表,使用 list.Remove() 删除所有我不需要的文件。

第一次删除后,它会出错

Collection was modified; enumeration operation might not execute

代码是:

string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);

//Converting to list, to use list.Remove rather than rewriting entire array at each delete
var list = new List<string>(files);
foreach (string readFile in list)
{
if (Path.GetExtension(readFile) != ".cs") //|| Path.GetExtension(readFile) != ".dll")
{
//remove, as we don't currently care about non cs files.
list.Remove(readFile);
}
}

//Converting back to string array for use in the rest of the program
files = list.ToArray();
}

我也试过 RemoteAt(),它产生了同样的错误。

string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);

//Converting to list, to use list.Remove rather than rewriting entire array at each delete
var list = new List<string>(files);
int i = 0;
for(int i=0; i<list.Count();i++)
{
if (Path.GetExtension(readFile) != ".cs") //|| Path.GetExtension(readFile) != ".dll")
{
//remove, as we don't currently care about non cs files.
list.RemoveAt(i);
}
i++;
}

//Converting back to string array for use in the rest of the program
files = list.ToArray();
}

克服此错误的任何建议,因为某些目录中将包含超过 500 个文件,我希望尽可能避免重写字符串数组。

我已阅读以下 SO 问题:

How to remove item from list in C#?

C# error Collection was modified; enumeration operation might not execute

Enumerations Foreach Loop C#

"List.Remove" in C# does not remove item?

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeat?view=netframework-4.8

最佳答案

您还可以以相反的顺序使用 for 循环,这样删除的条目就不会影响循环。

for (int x = list.Count-1; x >= 0; x--)
{
string readFile = list[x];
// ...
list.Remove(readFile);
}

关于C# list.remove 在 foreach 循环中抛出枚举操作错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907313/

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