Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.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# 是否可以在EntityCollection上实现RemoveAll()<;T>;?_C#_.net_Linq_Entity Framework - Fatal编程技术网

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

C# 是否可以在EntityCollection上实现RemoveAll()<;T>;?,c#,.net,linq,entity-framework,C#,.net,Linq,Entity Framework,我有一个问题类似于,但与EntityCollection有关 EntityCollection实现了Remove(),允许您一次从列表中删除单个项。但是,我想实现一个可以一次删除多个项的扩展方法,类似于IList的RemoveAll(谓词匹配)方法 一个想法是循环浏览列表,并删除项目。比如: public static void RemoveAll<T>(this EntityCollection<T> collection, Predicate<T> mat

我有一个问题类似于,但与
EntityCollection
有关

EntityCollection
实现了
Remove()
,允许您一次从列表中删除单个项。但是,我想实现一个可以一次删除多个项的扩展方法,类似于
IList
RemoveAll(谓词匹配)
方法

一个想法是循环浏览列表,并删除项目。比如:

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));
}
publicstaticvoidremoveall(此EntityCollection集合,谓词匹配),其中T:EntityObject
{
foreach(集合中的TO)
{
if(匹配(o))
收集。移除(o);
}
}
但是,这将引发异常,因为您无法修改正在迭代的集合


另一个想法是建立一个要删除的项目的临时列表,然后循环该列表并从集合中删除每个项目。然而,在我看来,这似乎效率低下。有更好的实现吗?

正如我在评论中所说的,在次要列表上迭代可能是这里唯一安全的选择

您可以通过以下方式实现它:

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));
}
public static void RemoveAll(此EntityCollection集合,
谓词匹配),其中T:EntityObject
{
if(match==null){
抛出新的ArgumentNullException(“匹配”);
}
集合。其中(实体=>匹配(实体))
.ToList().ForEach(entity=>collection.Remove(entity));
}

不确定效率有多低,但我担心在这里,迭代第二个列表是唯一安全的选择。就实现而言,使用LINQ您可以得到一些非常简短的东西。是的,我认为您是对的。.遗憾的是MS没有将
removehere
添加到
ICollection
接口。@CodesInChaos,将该要求添加到
ICollection
可能不值得(因为解决方法足够短)可以说,这会将不必要的工作推给实现者(大多数时候)。请注意,目前实现
ICollection
所需的方法中,没有一种方法通常采用谓词或委托。@FrédéricHamidi我认为没有好的解决方法。实施策略取决于集合。
removehere
的实现需要与
HashSet
List
LinkedList
,…完全不同,这比我的实现要好得多<代码>+1