开发者

should i use Except or Contains when dealing with HashSet or so in Linq

开发者 https://www.devze.com 2023-03-30 22:09 出处:网络
Look at this: var query = myDic.Select(x => x.Key).Except(myHashSet); or var query = myDic.Select(x => x.Key).where(y=>!myHashSet.Contains(y))

Look at this:

 var query = myDic.Select(x => x.Key).Except(myHashSet);

or

 var query = myDic.Select(x => x.Key).where(y=>!myHashSet.Contains(y))

i guess a O(1) version of Contains开发者_如何学JAVA will be invoked due to polymophism in first case. Don't know about except though.

Update

Exept is also O(1) in my case.

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


If your myDic is a normal .NET Dictionary then I will go with

myDic.Keys.Except(myHashSet)

for readability.

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's answer is O(n+m) too but most probably it will be faster than your O(n+m) solution.


var query = myDic.Select(x => x.Key).Except(myHashSet);

The Except will be the extension on IEnumerable (the result of Select). This is not O(1)

myHashSet.Contains(y) Is indeed calling the member function, which is O(n)


Consider

new HashSet<K>(myDic.Select(x => x.Key)).ExceptWith(myHashSet);

Also look at HashSet<>.SymmetricExceptWith()

0

精彩评论

暂无评论...
验证码 换一张
取 消