atlantis
atlantis

Reputation: 3126

HashSet conversion to List

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.

Upvotes: 47

Views: 91302

Answers (4)

user3083619
user3083619

Reputation:

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

Upvotes: 9

Simon Fox
Simon Fox

Reputation: 10561

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

Upvotes: 8

Graviton
Graviton

Reputation: 83254

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.

Upvotes: 99

Jon Skeet
Jon Skeet

Reputation: 1500514

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

Upvotes: 20

Related Questions