HashSet conversion to List

风流意气都作罢 提交于 2019-12-30 07:51:23

问题


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


来源:https://stackoverflow.com/questions/1430987/hashset-conversion-to-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!