我有一个类似于 this one 的问题, 但属于 EntityCollection<>
.
EntityCollection
工具 Remove()
,允许您一次从列表中删除一个单个项。但是,我想实现一个可以一次删除多个项目的扩展方法,类似于 IList<T>
的 RemoveAll(Predicate<T> match)
方法。
一个想法是遍历列表并删除项目。像这样的东西:
public static void RemoveAll<T>(this EntityCollection<T> collection, Predicate<T> match) where T : EntityObject
{
foreach (T o in collection)
{
if (match(o))
collection.Remove(o);
}
}
但是,这将引发异常,因为您无法修改正在迭代的集合。
另一个想法是构建一个要删除的项目的临时列表,然后遍历那个列表并从集合中删除每个项目。但是,这对我来说似乎效率低下。有没有更好的实现方式?
最佳答案
正如我在评论中所说,迭代次级列表可能是这里唯一安全的选择。
你可以用类似的东西来实现它:
public static void RemoveAll<T>(this EntityCollection<T> collection,
Predicate<T> match) where T : EntityObject
{
if (match == null) {
throw new ArgumentNullException("match");
}
collection.Where(entity => match(entity))
.ToList().ForEach(entity => collection.Remove(entity));
}
关于c# - 是否可以在 EntityCollection<T> 上实现 RemoveAll()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031059/