Tutorial :HashSet conversion to List



Question:

I have looked this up on the net but I am asking this to make sure I haven't missed out on something. Is there a built-in function to convert HashSets to Lists in C#? I need to avoid duplicity of elements but I need to return a List.


Solution:1

Here's how I would do it:

   using System.Linq;     HashSet<int> hset = new HashSet<int>();     hset.Add(10);     List<int> hList= hset.ToList();  

HashSet is, by definition, containing no duplicates. So there is no need for Distinct.


Solution:2

Two equivalent options:

HashSet<string> stringSet = new HashSet<string> { "a", "b", "c" };  // LINQ's ToList extension method  List<string> stringList1 = stringSet.ToList();  // Or just a constructor  List<string> stringList2 = new List<string>(stringSet);  

Personally I'd prefer calling ToList is it means you don't need to restate the type of the list.

Contrary to my previous thoughts, both ways allow covariance to be easily expressed in C# 4:

    HashSet<Banana> bananas = new HashSet<Banana>();              List<Fruit> fruit1 = bananas.ToList<Fruit>();      List<Fruit> fruit2 = new List<Fruit>(bananas);  


Solution:3

There is the Linq extension method ToList<T>() which will do that (It is defined on IEnumerable<T> which is implemented by HashSet<T>).

Just make sure you are using System.Linq;

As you are obviously aware the HashSet will ensure you have no duplicates, and this function will allow you to return it as an IList<T>.


Solution:4

List<ListItemType> = new List<ListItemType>(hashSetCollection);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »