C# | Create HashSet from another collection
In C#, you can create a HashSet<T> from another collection by using the HashSet<T> constructor that takes an IEnumerable<T> parameter. Here’s an example:
C#
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List< int > numbers = new List< int > { 1, 2, 3, 4, 5 };
HashSet< int > numberSet = new HashSet< int >(numbers);
Console.WriteLine( "Contents of HashSet:" );
foreach ( int number in numberSet)
{
Console.WriteLine(number);
}
}
}
|
Output
Contents of HashSet:
1
2
3
4
5
A HashSet is an unordered collection of the unique elements. It comes under 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. You can create a HashSet from another collection by passing the collection as an argument while creating the object of HashSet. Below given are some examples to understand the implementation in a better way: Example 1:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet = new HashSet< int >();
for ( int i = 0; i < 5; i++) {
mySet.Add(i * 2);
}
HashSet< int > mySet_new = new HashSet< int >(mySet);
Console.WriteLine("The elements in newly created HashSet are : ");
foreach ( int i in mySet_new)
{
Console.WriteLine(i);
}
}
}
|
Example 2:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< string > mySet = new HashSet< string >();
mySet.Add("Delhi");
mySet.Add("Noida");
mySet.Add("Chandigarh");
mySet.Add("New York");
mySet.Add("Bangalore");
HashSet< string > mySet_new = new HashSet< string >(mySet);
Console.WriteLine("The elements in newly created HashSet are : ");
foreach ( string i in mySet_new)
{
Console.WriteLine(i);
}
}
}
|
Last Updated :
22 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...