Jee*_*eby 3 .net c# 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.KitGroupID))
ProductToTransfer.KitGroups.Remove(kg);
else
{
// Loop through the kit items and do other stuff
//...
}
}
Run Code Online (Sandbox Code Playgroud)
它迭代到集合中的第二个对象时抛出的错误是:"在枚举期间修改了EntitySet"
我知道我可以创建一个我想删除的KitGroup对象(甚至只是ID)的新集合,然后再循环通过这些对象,并从集合中删除它们,但这似乎是不必要的额外代码..任何人都可以建议一种更优雅的方式来实现同样的目标吗?
Jak*_*ake 14
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
//...
}
}
Run Code Online (Sandbox Code Playgroud)
或者如果KitGroups List<T>
已经是类型......
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
//...
}
Run Code Online (Sandbox Code Playgroud)
IEnumerable<T>
如果要RemoveAll()
使用扩展方法定义行为,也可以在另一个方法上使用此第二种方法.请确保您不要尝试RemoveAll()
在LINQ实体表上使用,因为它inKitGroupExclusion.Contains()
不会被转换为SQL.
编辑:刚才意识到它不是一个列表,只是一个EntitySet
,所以你需要使用第一种方法.