2

I have two HashSets – setA and setB.

  1. How can we find the complement of setA and setB?
  2. Is the code for intersection the best way to find intersection?

CODE

 string stringA = "A,B,A,A";
 string stringB = "C,A,B,D";

 HashSet<string> setA = new HashSet<string>(stringA.Split(',').Select(t => t.Trim()));
 HashSet<string> setB = new HashSet<string>(stringB.Split(',').Select(t => t.Trim()));

 //Intersection - Present in A and B
 HashSet<string> intersectedSet = new HashSet<string>( setA.Intersect(setB));

 //Complemenet - Present in A; but not present in B

UPDATE:

Use OrdianlIgnoreCase for ignoring case sensitvity How to use HashSet<string>.Contains() method in case -insensitive mode?

REFERENCE:

  1. What is the difference between HashSet<T> and List<T>?
  2. Intersection of multiple lists with IEnumerable.Intersect()
  3. Comparing two hashsets
  4. Compare two hashsets?
  5. Quickest way to find the complement of two collections in C#
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

2 Answers2

2

1 - How can we find the complement of setA and setB?

Use HashSet<T>.Except Method

//Complemenet - Present in A; but not present in B
HashSet<string> ComplemenetSet = new HashSet<string>(setA.Except(setB));

try it with following string.

string stringA = "A,B,A,E";
string stringB = "C,A,B,D";

ComplementSet will contain E

2 - Is the code for intersection the best way to find intersection?

Probably, YES

Habib
  • 219,104
  • 29
  • 407
  • 436
2

You can use Except to get the complement of A or B. To get a symmetric complement, use SymmetricExceptWith.

setA.SymmetricExceptWith(setB);

Note that this modifies setA. To get the intersection, there are two methods: Intersect, which creates a new HashSet, and IntersectWith, which modifies the first:

// setA and setB unchanged
HashSet<string> intersection = setA.Intersect(setB);

// setA gets modified and holds the result
setA.IntersectWith(setB);
McGarnagle
  • 101,349
  • 31
  • 229
  • 260