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}
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.
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.
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);
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
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