
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create HashSet from another collection in C#
To create HashSet from another Collection, the code is as follows−
Example
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(100); set1.Add(200); set1.Add(300); Console.WriteLine("HashSet created from another collection..."); foreach(int i in set1){ Console.WriteLine(i); } HashSet<int> set2 = new HashSet<int>(set1); Console.WriteLine("HashSet created from another collection..."); foreach(int i in set2){ Console.WriteLine(i); } } }
Output
This will produce the following output −
HashSet created from another collection... 100 200 300 HashSet created from another collection... 100 200 300
Example
Let us now see another example −
using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<string> set1 = new HashSet<string>(); set1.Add("Jacob"); set1.Add("Tom"); set1.Add("Harry"); set1.Add("Harry"); set1.Add("Tom"); set1.Add("Harry"); Console.WriteLine("HashSet created from another collection..."); foreach(string i in set1){ Console.WriteLine(i); } HashSet<string> set2 = new HashSet<string>(set1); Console.WriteLine("HashSet created from another collection..."); foreach(string i in set2){ Console.WriteLine(i); } } }
Output
This will produce the following output −
HashSet created from another collection... Jacob Tom Harry HashSet created from another collection... Jacob Tom Harry
Advertisements