为什么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?
问题描述
为什么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< TSource>方法(IEnumerable< TSource>,HashSet< TSource>)重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!