Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet conversion to List

Tags:

c#

list

set

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.

like image 892
atlantis Avatar asked Sep 16 '09 04:09

atlantis


People also ask

Can we convert list to HashSet in Java?

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.

How do you convert a set into a list?

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.

Can we convert set to list in Java?

We can simply convert a Set into a List using the constructor of an ArrayList or LinkedList.

What is the difference between ArrayList and HashSet?

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.


2 Answers

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.

like image 135
Graviton Avatar answered Oct 13 '22 00:10

Graviton


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); 
like image 21
Jon Skeet Avatar answered Oct 13 '22 01:10

Jon Skeet