Last Updated : 11 Jul, 2025
A
HashSetis an unordered collection of the unique elements. It is found in
System.Collections.Genericnamespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list.
HashSet .IntersectWith(IEnumerable ) Methodis used to modify the current
HashSetobject to contain only elements that are present in that object and in the specified collection.
Syntax:mySet1.IntersectWith(mySet2)
Here
mySet1and
mySet2are the two HashSets.
Exception:This method will give
ArgumentNullExceptionif the HashSet is
null. Below given are some examples to understand the implementation in a better way:
Example 1: CSHARP
// C# code to find Intersection
//of two HashSets
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of integers
HashSet<int> mySet1 = new HashSet<int>();
// Creating a HashSet of integers
HashSet<int> mySet2 = new HashSet<int>();
// Inserting even numbers less than
// equal to 10 in HashSet mySet1
Console.WriteLine("Elements in Set 1 :");
for (int i = 0; i < 5; i++) {
mySet1.Add(i * 2);
Console.WriteLine(i * 2);
}
// Inserting odd numbers less than
// equal to 10 in HashSet mySet2
Console.WriteLine("Elements in Set 2 : ");
for (int i = 0; i < 5; i++) {
mySet1.Add(i * 2 + 1);
Console.WriteLine(i *2 + 1);
}
// Creating a new HashSet that contains
// the Intersection of both the HashSet mySet1 & mySet2
HashSet<int> ans = new HashSet<int>(mySet1);
ans.IntersectWith(mySet2);
// Printing the Intersection of both the HashSets
// It should show no element in the output
// as there is no element common in both
// the HashSets
foreach(int i in ans)
{
Console.WriteLine(i);
}
}
}
Output:
Elements in Set 1 : 0 2 4 6 8 Elements in Set 2 : 1 3 5 7 9Example 2: CSHARP
// C# code to find Intersection
// of two HashSets
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of strings
HashSet<string> mySet1 = new HashSet<string>();
// Creating a HashSet of strings
HashSet<string> mySet2 = new HashSet<string>();
// Inserting elements in mySet1
mySet1.Add("Hello");
mySet1.Add("Geeks");
mySet1.Add("GeeksforGeeks");
// Inserting elements in mySet2
mySet2.Add("Geeks");
mySet2.Add("and");
mySet2.Add("GeeksforGeeks");
mySet2.Add("are");
mySet2.Add("the");
mySet2.Add("best");
// Creating a new HashSet that contains
// the Intersection of both the HashSet mySet1 & mySet2
HashSet<string> ans = new HashSet<string>(mySet1);
ans.IntersectWith(mySet2);
// Printing the Intersection of both the HashSet
foreach(string i in ans)
{
Console.WriteLine(i);
}
}
}
Output:
Geeks GeeksforGeeksReference:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4