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

有帮助吗?

解决方案

我将如何做到这一点:

   using System.Linq;
   HashSet<int> hset = new HashSet<int>();
   hset.Add(10);
   List<int> hList= hset.ToList();

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

其他提示

两个等效选项:

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

Linq扩展方法ToList<T>()将执行此操作(它在IEnumerable<T>上定义,由HashSet<T>实现)。

确保您using System.Linq;

正如您明显知道HashSet将确保您没有重复项,此功能将允许您将其作为IList<T>返回。

List<ListItemType> = new List<ListItemType>(hashSetCollection);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top