问题描述
看看这个:
var query = myDic.Select(x => x.Key).Except(myHashSet);
或
var query = myDic.Select(x => x.Key).where(y=>!myHashSet.Contains(y))
我猜想由于第一种情况的多态性,将调用O(1)版本的Contains
.不过不知道except
.
i guess a O(1) version of Contains
will be invoked due to polymophism in first case.Don't know about except
though.
更新
在我的情况下,专家也是O(1).
Exept is also O(1) in my case.
为什么linq的`except`扩展方法没有< TSource>方法(IEnumerable< TSource>,HashSet< TSource>)重载吗?
推荐答案
如果您的myDic
是普通的.NET词典,那么我将使用
If your myDic
is a normal .NET Dictionary then I will go with
myDic.Keys.Except(myHashSet)
以提高可读性.
要说出您的选择,第一个是O(n + m),而第二个是O(n),这两个都不能告诉您哪个集合最先完成.如有疑问,两匹马都要比赛.
To speak of your options, the first one is O(n+m) whereas the second O(n), neither of which tells you which finishes first for your collection size. When in doubt race both the horses.
@sehe的答案也是O(n + m),但很可能比您的O(n + m)解决方案要快.
@sehe's answer is O(n+m) too but most probably it will be faster than your O(n+m) solution.
这篇关于我在Linq中处理HashSet时应使用Except还是Contains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!