What is the SetEquals() method in C#?
Overview
The HashSet<T> generic class in the System.Collections.Generic namespace provides the SetEquals() method. It is used to determine if a HashSet<T> object and the passed input collection contain the same elements.
The illustration below shows how the SetEquals() method works.
Syntax
public bool SetEquals (System.Collections.Generic.IEnumerable<T> other);
Parameters
This method takes a collection IEnumerable<T> as input and compares its elements to the HashSet elements.
Return value
SetEquals() returns true if the HashSet and input collection contain the same elements, and returns false otherwise.
Things to note
-
The
SetEquals()method ignores duplicate items when comparing set equality. -
The order of elements is also ignored.
-
SetEquals()is an operation, where is the count of elements in the passed collection of elements and is the number of elements in theHashSet<T>. -
In a special case where the passed input collection is also a
HashSet<T>with the same equality comparer as the currentHashSet<T>object, the method becomes an operation, where is the number of elements in the passed input collection. -
SetEquals()throws an exception if the input collection is null. -
This method does not change the state of the
HashSet<T>.
Code
The code below shows how the SetEquals() method works in C#.
using System;using System.Collections.Generic;class HashSetEquals{static void Main(){HashSet<int> numSet = new HashSet<int>();numSet.Add(1);numSet.Add(5);numSet.Add(9);numSet.Add(11);numSet.Add(15);numSet.Add(6);Console.WriteLine("HashSet Elements : ");PrintSet(numSet);List<int> otherList = new List<int>{9,11,15,6,5,1};Console.WriteLine("Input Collection 1 : {0}", string.Join(" ", otherList.ToArray()));bool isSetEquals = numSet.SetEquals(otherList);Console.WriteLine($"Is HashSet equal to Input Collection 1 ?: {isSetEquals}");otherList = new List<int>{9,11,23,6,5,1};Console.WriteLine("Input Collection 2 : {0}", string.Join(" ", otherList.ToArray()));isSetEquals = numSet.SetEquals(otherList);Console.WriteLine($"Is HashSet equal to Input Collection 2 ? : {isSetEquals}");}private static void PrintSet(HashSet<int> set){Console.Write("{");foreach (int i in set){Console.Write(" {0}", i);}Console.WriteLine(" }");}}
Explanation
-
In the example above, we create a
HashSetof integers and add a few numbers to it. -
We also create two lists of integers, one with the same elements as the HashSet and another with a few different elements.
-
We call
SetEquals()with the first list of integers as input. Since the list has the same elements as theHashSet,SetEquals()returnsTrue. -
We call
SetEquals()again with the second list of integers as input. Since the second list has a few different elements from theHashSet,SetEquals()returnsfalse. -
We print the elements of the
HashSetand both lists.