tags:

views:

1002

answers:

3

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.

+6  A: 

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.

Ngu Soon Hui
Related to this, if I have an ordered list and I do orderedList.Distinct().ToList() could you tell me if it retains the order in the orderedList? It serves my purpose if it ensures that it always retains the first occurence of the duplicate element and gets rid of the later occurence.(I have the list ordered by relevance...need the more relevant one to be retained)
atlantis
@Ngu there is no point using Distinct() on a HashSet as there will be no duplicates anyway
Simon Fox
Yes, the order is retained.
Ngu Soon Hui
@Simon...Exactly what I was wondering...any idea why there is a Distinct() method available on the HashSet to start with?
atlantis
+2  A: 

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 your 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>.

Simon Fox
+2  A: 

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);
Jon Skeet