c# - 是否可以在 EntityCollection<T> 上实现 RemoveAll()?

标签 c# .net linq entity-framework

我有一个类似于 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/

相关文章:

C# 是否可以将 groupBox 标题设为单选按钮?

c# - 使此 LINQ 语句返回 T 而不是 Task<T>

c# - 权限处理的模式/设计建议

.NET Framework 4.0 和使用 2.0 的程序集

c# - 如果在 ThreadPool 的线程正在写入文件时应用程序关闭,会发生什么情况?

c# - MongoDB C# 驱动程序——创建索引

c# - 我应该如何从一个 Controller 操作返回两个对象列表?

c# - 选择投影中的索引

c# - 使用 Compact Framework 在数据网格中设置列宽

c# - 作为 Windows 服务运行时的 PCSC.InvalidContextException