C# | Intersection of two HashSets
A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. 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) Method is used to modify the current HashSet object to contain only elements that are present in that object and in the specified collection.
Syntax:
mySet1.IntersectWith(mySet2)
Here mySet1 and mySet2 are the two HashSets.
Exception: This method will give ArgumentNullException if the HashSet is null.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet1 = new HashSet< int >();
HashSet< int > mySet2 = new HashSet< int >();
Console.WriteLine( "Elements in Set 1 :" );
for ( int i = 0; i < 5; i++) {
mySet1.Add(i * 2);
Console.WriteLine(i * 2);
}
Console.WriteLine( "Elements in Set 2 : " );
for ( int i = 0; i < 5; i++) {
mySet1.Add(i * 2 + 1);
Console.WriteLine(i *2 + 1);
}
HashSet< int > ans = new HashSet< int >(mySet1);
ans.IntersectWith(mySet2);
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
9
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< string > mySet1 = new HashSet< string >();
HashSet< string > mySet2 = new HashSet< string >();
mySet1.Add( "Hello" );
mySet1.Add( "Geeks" );
mySet1.Add( "GeeksforGeeks" );
mySet2.Add( "Geeks" );
mySet2.Add( "and" );
mySet2.Add( "GeeksforGeeks" );
mySet2.Add( "are" );
mySet2.Add( "the" );
mySet2.Add( "best" );
HashSet< string > ans = new HashSet< string >(mySet1);
ans.IntersectWith(mySet2);
foreach ( string i in ans)
{
Console.WriteLine(i);
}
}
}
|
Output:
Geeks
GeeksforGeeks
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...