Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to compare 2 hash sets and take out the differences

Tags:

c#

hashset

I have 2 hash sets like this.

Hash_1 = {1, 2, 3, 4, 5}
Hash_2 = {4, 5, 6, 7, 8}

I am using C#

I want to compare those two sets and want to get the output like

Hash_3 = {1, 2, 3, 6, 7, 8}
like image 743
maxrena Avatar asked May 31 '19 05:05

maxrena


People also ask

How do you compare two hash sets?

The equals() method of java. util. HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order.

How do I compare two sets of strings in Java?

The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.

How do you check if two sets are equal in C#?

C# | Check if two HashSet<T> objects are equal Equals(Object) Method which is inherited from the Object class is used to check if a specified HashSet<T> object is equal to another HashSet<T> object or not. Syntax: public virtual bool Equals (object obj);


1 Answers

Or you could use SymmetricExceptWith

Modifies the current HashSet<T> object to contain only elements that are present either in that object or in the specified collection, but not both.

var h1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
var h2 = new HashSet<int>() { 4, 5, 6, 7, 8 };

h1.SymmetricExceptWith(h2);

Console.WriteLine(string.Join(",", h1));

Output

1,2,3,7,6,8

Internally it just uses

foreach (T item in other)
{
   if (!Remove(item))
   {
      AddIfNotPresent(item);
   }
}

Source Code here

like image 65
TheGeneral Avatar answered Oct 13 '22 20:10

TheGeneral