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.
There are four ways to convert ArrayList to HashSet :Using constructor. Using add() method by iterating over each element and adding it into the HashSet. Using addAll() method that adds all the elements in one go into the HashSet. Using stream.
Approach #1 : Using list(set_name) . Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.
We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.
ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With