2010-06-02 64 views
2

从EntitySet的卸下实体我有了这个代码...看上去不错,优雅,但显然在通过它迭代框架不喜欢它,当我惹的集合:期间迭代

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  
//...  
}  
} 

当它遍历集合中的第二个对象,它抛出的错误是:

我知道我可以创建KitGroup对象的一个​​新的集合(甚至只是标识)“EntitySet的枚举过程中被修改”,我想删除,然后再循环以循环这些,并将它们从集合中删除,但这看起来像不必要的e xtra代码......任何人都可以提出实现同样目标的更优雅的方式吗?

回答

12
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是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  
    //...  
} 

您还可以,如果你想定义RemoveAll()行为与扩展方法使用第二种方法在另一个IEnumerable<T>。请确保您不要尝试在LINQ实体表上使用RemoveAll(),因为inKitGroupExclusion.Contains()不会被翻译成SQL。

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

+0

哇真棒......我需要做的就是将它转换为列表。所以它只是因为它是一个EntitySet,我无法删除枚举中的集合项......这是为什么? 感谢堆,我知道这将是一个简单的解决方案这个问题:) – Jeeby 2010-06-02 06:08:08

+2

@Gregorius这不是事实,它是一个'EntitySet',这是事实,你是从你正在枚举的对象中删除。当你从原始的EntitySet中删除时,调用'ToList'实例化一个新的'List'对象来枚举。您将不得不使用相同的过程从“List”或任何其他集合中删除项目。 – Jake 2010-06-02 06:10:43

+0

ahhh ...这很有道理。谢谢杰克,非常感谢 – Jeeby 2010-06-02 07:31:03