C#list.remove在foreach循环中删除引发枚举操作错误

时间:2019-04-29 16:21:57

标签: c# list foreach

我已经查看了与我的以及谷歌搜索相关的多个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://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.8

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

3 个答案:

答案 0 :(得分:1)

如果我改变

foreach (string readFile in list)

foreach (string readFile in list.ToList())

有效。

我的猜测是该列表。删除会更改原始列表,并使枚举无效。

答案 1 :(得分:1)

您可以在List上使用RemoveAll方法:

list.RemoveAll(readFile => Path.GetExtension(readFile) != ".cs");

这将删除所有与您的谓词匹配的内容,并返回其删除的项目数。

答案 2 :(得分:1)

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

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