How to check if HashSet and collection share common items in C#
The HashSet<T> generic class in the System.Collections.Generic Overlaps() method, which is used to determine if a HashSet<T> and another IEnumerable<T> share common elements.
Syntax
public bool Overlaps (System.Collections.Generic.IEnumerable<T> other);
-
The
Overlaps()method takes anIEnumerable<T> as input, and returnscollection specialized classes for data storage and retrieval classes. Trueif theHashSet<T>and the input collection have at least one element in common. -
It returns
Falseif there are no common elements between theHashSet<T>and the input collection.
Things to note
-
This method is an O(n) operation, where n counts elements in the
HashSet<T>. -
The
Overlap()method throws an exception if the input collection isnull. -
This method does not change the state of the
HashSet<T>.
The linear time complexity O(n) means that any particular algorithm takes proportionally more time to finish as the input grows.
Code
In the example below, we create a HashSet of integers and add a few numbers.
We also create two Lists of integers, one that has common elements with the HashSet, and another with no common elements.
using System;using System.Collections.Generic;class HashSetOverlap {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};Console.WriteLine("Input List 1: {0}",string.Join(" ", otherList.ToArray()));bool hasCommonElem = numSet.Overlaps(otherList);Console.WriteLine("Does HashSet share common elements with List 1? : {0}", hasCommonElem);otherList = new List<int>{29,34,90};Console.WriteLine("Input List 2: {0}",string.Join(" ", otherList.ToArray()));hasCommonElem = numSet.Overlaps(otherList);Console.WriteLine("Does HashSet share common elements with List 2 ? : {0}", hasCommonElem);}private static void PrintSet(HashSet<int> set) {Console.Write("{");foreach (int i in set) {Console.Write(" {0}", i);}Console.WriteLine(" }");}}
Explanation
In the code above, we call the Overlaps() method with the first list of integers as input. Since it has a few common elements with HashSet, Overlaps() returns True and it is displayed in the output.
We again call the Overlaps() method with the second list of integers as input. Since it has no common elements with HashSet, Overlaps() returns False, and this is also displayed in the output.
We print the elements of the HashSet and both lists. The program prints the output below and exits.
HashSet Elements :
{ 1 5 9 11 15 6 }
Input List 1: 9 11
Does HashSet share common elements with List 1? : True
Input List 2: 29 34 90
Does HashSet share common elements with List 2 ? : False