Conversion between List and HashSet in C#
This post will discuss how to convert a List to HashSet in C# and vice versa.
Convert List to HashSet:
1. Using HashSet Constructor
We can use the HashSet constructor, which takes an IEnumerable<T> to construct a new instance of the HashSet<T> class containing distinct elements of the list.
Note that since HashSet contains distinct elements, it’ll discard any repeated elements in the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 3, 3, 2, 4 }; HashSet<int> set = new HashSet<int>(list); Console.WriteLine(String.Join(",", set)); } } /* Output: 1,3,2,4 */ |
2. Enumerable.ToHashSet() method (System.Linq)
We can use ToHashSet() method to create a HashSet<T> from an IEnumerable<T>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int> { 1, 3, 3, 2, 4 }; HashSet<int> set = list.ToHashSet(); Console.WriteLine(String.Join(",", set)); } } /* Output: 1,3,2,4 */ |
Convert HashSet to List:
1. Using List Constructor
We can use the List constructor, which takes an IEnumerable<T> to construct a new instance of the List<T> containing all elements of the set.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 }; List<int> list = new List<int>(set); Console.WriteLine(String.Join(",", list)); } } /* Output: 1,2,3,4,5 */ |
2. Enumerable.ToList() method (System.Linq)
We can use ToList() method to create a List<T> from an IEnumerable<T>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 }; List<int> list = set.ToList(); Console.WriteLine(String.Join(",", list)); } } /* Output: 1,2,3,4,5 */ |
That’s all about conversion between List and HashSet in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)