Reputation:
I am aware of hashsetA.Except(hashsetB)
to remove elements from hashsetA
that exist in hashsetB
. However, I want to remove elements from hashsetA
that don't exist in hashsetB
.
Currently I just copy hashsetA
to a new Hashset
then use ExceptWith()
twice:
hashsetC = new HashSet<var>(hashsetA);
hashsetC.ExceptWith(hashsetB);
hashsetA.ExceptWith(hashsetC);
The performance of this is plenty good enough for my purposes, but I was wondering if there's a built in method to make this faster/more concise? Or am I missing an obvious way to select from the sets?
Upvotes: 1
Views: 6742
Reputation: 62012
Simply use IntersectWith
method.
hashsetA.IntersectWith(hashsetB);
Upvotes: 3
Reputation: 3990
res = hashsetA.Where(p=> hashsetB.Contains(p)).
Given that lookup in a Hashset is O(1), that should sum to O(n).
Upvotes: 1