Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set A minus Set B

Tags:

c#

.net

set

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);
}
like image 487
phcoding Avatar asked Oct 21 '25 04:10

phcoding


2 Answers

You can use the Except() method. Here is the code:

HashSet<int> A_minus_B = new HashSet<int>(A.Except(B)); 
like image 145
Hossein Narimani Rad Avatar answered Oct 22 '25 16:10

Hossein Narimani Rad


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.

like image 31
phadaphunk Avatar answered Oct 22 '25 16:10

phadaphunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!