我已经看过这件事在网络上,但我要求是为了确保我没有错过了一些东西。 是否有一个内置的功能HashSets转换为列表中的C#? 我需要避免的元件的口是心非,但我需要返回一个列表。
Answer 1:
这是我会怎么做:
using System.Linq;
HashSet<int> hset = new HashSet<int>();
hset.Add(10);
List<int> hList= hset.ToList();
HashSet的是,根据定义,不含有重复。 因此,有没有必要Distinct
。
Answer 2:
两个等价的选项:
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);
我个人倒更叫ToList
是不是就意味着你不需要重申列表的类型。
相反,我以前的想法,左右逢源允许协方差在C#4很容易地表示:
HashSet<Banana> bananas = new HashSet<Banana>();
List<Fruit> fruit1 = bananas.ToList<Fruit>();
List<Fruit> fruit2 = new List<Fruit>(bananas);
Answer 3:
还有就是LINQ的扩展方法ToList<T>()
其将这样做(它是上定义IEnumerable<T>
其通过实现HashSet<T>
只要确保你正在using System.Linq;
正如你显然也意识到了HashSet
将确保你有没有重复,这个功能可以让你把它偿还作为一个IList<T>
Answer 4:
List<ListItemType> = new List<ListItemType>(hashSetCollection);
文章来源: HashSet conversion to List