HashSet转换为List

atl*_*tis 25 c# list set

我在网上看了这个,但我要求这一点确保我没有错过任何东西.是否有内置函数将HashSets转换为C#中的列表?我需要避免重复的元素,但我需要返回一个List.

Gra*_*ton 66

我是这样做的:

   using System.Linq;
   HashSet<int> hset = new HashSet<int>();
   hset.Add(10);
   List<int> hList= hset.ToList();
Run Code Online (Sandbox Code Playgroud)

根据定义,HashSet不包含重复项.所以没有必要Distinct.


Jon*_*eet 14

两个等价选项:

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);
Run Code Online (Sandbox Code Playgroud)

我个人更喜欢打电话ToList,这意味着你不需要重述列表的类型.

与我之前的想法相反,两种方式都允许在C#4中轻松表达协方差:

    HashSet<Banana> bananas = new HashSet<Banana>();        
    List<Fruit> fruit1 = bananas.ToList<Fruit>();
    List<Fruit> fruit2 = new List<Fruit>(bananas);
Run Code Online (Sandbox Code Playgroud)


Sim*_*Fox 6

有Linq扩展方法ToList<T>()可以做到这一点(它的定义由IEnumerable<T>哪个实现HashSet<T>).

请确保你是 using System.Linq;

因为你显然知道这HashSet将确保你没有重复,这个功能将允许你作为一个返回它IList<T>.


小智 5

List<ListItemType> = new List<ListItemType>(hashSetCollection);
Run Code Online (Sandbox Code Playgroud)