gpt4 book ai didi

asp.net-mvc - 如何克服此错误 :- Collection was modified; enumeration operation may not execute.“

转载 作者:行者123 更新时间:2023-12-02 15:35:55 31 4
gpt4 key购买 nike

我有以下方法:-

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);
}
}
}
}

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

foreach (var group in roleGroupsCopy)

关于如何克服此错误的建议?

最佳答案

您可以使用:

foreach (var group in roleGroupsCopy.ToList())

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

另一种方法是使用:

securityRole.Groups.RemoveAll(g => g.GroupID == currentGroups[c]);

关于asp.net-mvc - 如何克服此错误 :- Collection was modified; enumeration operation may not execute.“,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763056/

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