HashSet conversion to List

2019-04-17 23:59发布

问题:

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.

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



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


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



回答4:

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


标签: c# list set