Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在迭代期间从EntitySet中删除实体_C#_.net_Linq To Sql - Fatal编程技术网

C# 在迭代期间从EntitySet中删除实体

C# 在迭代期间从EntitySet中删除实体,c#,.net,linq-to-sql,C#,.net,Linq To Sql,我有这个密码。。。看起来不错,也很优雅,但是当我在遍历集合时弄乱了它,框架显然不喜欢它: foreach (KitGroup kg in ProductToTransfer.KitGroups) { // Remove kit groups that have been excluded by the user if (inKitGroupExclusions != null && inKitGroupExclusions.Contains(kg.KitG

我有这个密码。。。看起来不错,也很优雅,但是当我在遍历集合时弄乱了它,框架显然不喜欢它:

foreach (KitGroup kg in ProductToTransfer.KitGroups)    
{    
// Remove kit groups that have been excluded by the user    
if (inKitGroupExclusions != null && inKitGroupExclusions.Contains(kg.KitGroupID))    
    ProductToTransfer.KitGroups.Remove(kg);    
else    
{    
// Loop through the kit items and do other stuff    
//...    
}    
}
当它迭代到集合中的第二个对象时引发的错误是: “枚举期间修改了EntitySet”

我知道我可以创建一个新的KitGroup对象集合(甚至只是ID),然后再创建另一个循环来循环这些对象,并将它们从集合中删除,但这似乎是不必要的额外代码。。。有人能提出一种更优雅的方法来实现同样的目标吗

foreach (KitGroup kg in ProductToTransfer.KitGroups.ToList())    
{    
 // Remove kit groups that have been excluded by the user    
 if (inKitGroupExclusions != null && inKitGroupExclusions.Contains(kg.KitGroupID))    
     ProductToTransfer.KitGroups.Remove(kg);    
 else    
 {    
 // Loop through the kit items and do other stuff    
 //...    
 }    
}
或者如果KitGroups的类型已经是
列表

if(inKitGroupExclusion != null)
    ProductToTransfer.KitGroups.RemoveAll(x => inKitGroupExclusion.Contains(x));
foreach (KitGroup kg in ProductToTransfer.KitGroups)    
{    
    // Loop through the kit items and do other stuff    
    //...    
}
如果要使用扩展方法定义
RemoveAll()
行为,还可以在另一个
IEnumerable
上使用第二个方法。请确保不要尝试在LINQ实体表上使用
RemoveAll()
,因为
inKitGroupExclusion.Contains()
不会转换为SQL


编辑:刚刚意识到它不是一个列表,只是一个
实体集
,所以你需要使用第一种方法。

哇,太棒了。。。我所需要做的就是把它转换成一个列表。所以仅仅因为它是一个EntitySet,我无法删除枚举中的集合项。。。为什么会这样?多亏了heaps,我知道这个问题会有一个简单的解决方案:)@Gregoris这不是因为它是一个
实体集,而是因为您正在从正在枚举的对象中删除。调用
ToList
实例化一个新的
列表
对象,以便在从原始
实体集
中删除时进行枚举。您必须使用相同的过程从
列表
或任何其他集合中删除项目。啊。。。这很有道理。谢谢,杰克,非常感谢