【发布时间】:2009-09-16 04:45:27
【问题描述】:
我在网上查到了这个,但我问这个是为了确保我没有错过任何东西。 C# 中是否有将 HashSets 转换为 Lists 的内置函数?我需要避免元素的重复,但我需要返回一个列表。
【问题讨论】:
我在网上查到了这个,但我问这个是为了确保我没有错过任何东西。 C# 中是否有将 HashSets 转换为 Lists 的内置函数?我需要避免元素的重复,但我需要返回一个列表。
【问题讨论】:
我会这样做:
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);
【讨论】: