I am trying to take away one set from another in the most efficient way. So if I have the following sets A and B then A_minus_B should give {1, 2, 6}. Here is what I have although I am sure it is not the most efficient way.
HashSet<int> A = new HashSet<int>{ 1, 2, 3, 4, 5, 6 };
HashSet<int> B = new HashSet<int> { 3, 4, 5 };
HashSet<int> A_minus_B = new HashSet<int>(A);
foreach(int n in A){
if(B.Contains(n)) A_minus_B.Remove(n);
}
You can use the Except()
method. Here is the code:
HashSet<int> A_minus_B = new HashSet<int>(A.Except(B));
Use this :
var setA= new HashSet<int>();
var setB= new HashSet<int>();
...
var remaining = new HashSet<int>(setA);
remaining.ExceptWith(setB);
remaining
is your new filtered set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With