如何克服此错误:- 集合已修改;枚举操作可能无法执行。”

joh*_* Gu 2 asp.net-mvc entity-framework

我有以下方法:-

public void AssignGroupRole(int id, int[] selectedGroups, int[] currentGroups)
        {
            var roleGroups = FindRole(id).Groups;
            var roleGroupsCopy = roleGroups;
            var securityRole = FindRole(id);
            foreach (var group in roleGroupsCopy)
            {
                if (currentGroups != null)
                {
                    for (int c = 0; c < currentGroups.Count(); c++)
                    {
                        if (group.GroupID == currentGroups[c])
                        {

                            securityRole.Groups.Remove(group);
                        }
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

但我收到错误“集合已修改;枚举操作可能无法执行。” 在

foreach (var group in roleGroupsCopy)
Run Code Online (Sandbox Code Playgroud)

关于如何克服这个错误的任何建议?

Joh*_*son 5

您可以使用:

foreach (var group in roleGroupsCopy.ToList())
Run Code Online (Sandbox Code Playgroud)

调用 ToList() 将其复制到您循环的临时列表中。临时列表不会被修改。

另一种方法是使用:

securityRole.Groups.RemoveAll(g => g.GroupID == currentGroups[c]);
Run Code Online (Sandbox Code Playgroud)