为什么linq的`except`扩展方法没有Except< TSource>方法(IEnumerable< TSource>,HashSet< TSource>)重载吗? [英] why linq's `except` extension method does not have Except<TSource> Method (IEnumerable<TSource>,HashSet<TSource>) overload?

查看:75
本文介绍了为什么linq的`except`扩展方法没有Except< TSource>方法(IEnumerable< TSource>,HashSet< TSource>)重载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么linq的except扩展方法没有Except<TSource>方法(IEnumerable<TSource>,HashSet<TSource>)重载?

why linq's except extension method does not have Except<TSource> Method (IEnumerable<TSource>,HashSet<TSource>) overload?

例如

  var query = A.Except(B).where(x=>Criteria(x))

  foreach(item in query)
   {
     B.add(item);
     DoSomething(item);
   }

鉴于B是HashSet<T>,A是IEnumerable<T>ICollection<T> 在此,每次迭代Except都需要O(| B |)时间. 为什么没有一种方法会花费O(1)的时间,因为无论如何B都是Hashset.

Given B is HashSet<T>, A is IEnumerable<T> or ICollection<T> Here in each iteration Except take O(|B|) time. why there is not a method that just take O(1) time, as B is Hashset anyway.

更新

我的粗略方法是

var query = A.where(x=>!B.contains(x)).where(x=>Criteria(x))

推荐答案

每次迭代中都需要O(| B |)时间

Here in each iteration Except take O(|B|) time

不,不是. Except在内部使用类似于HashSet<T>的集合来实现.您可以查看 Jon Skeet的在Edulinq中提出的实施方案. B中的所有元素都放在HashSet<T>中,然后枚举A的元素;如果它们不在HashSet中(检查这是O(1)操作),则将按输出顺序返回它们.

No it doesn't. Except is implemented internally with a collection similar to HashSet<T>. You can have a look at Jon Skeet's proposed implementation in Edulinq. All elements in B are placed in a HashSet<T>, then elements of A are enumerated; if they're not in the HashSet (checking this is a O(1) operation), they are returned in the output sequence.

这篇关于为什么linq的`except`扩展方法没有Except&lt; TSource&gt;方法(IEnumerable&lt; TSource&gt;,HashSet&lt; TSource&gt;)重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆