C# HashSet 转换为 List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1430987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HashSet conversion to List
提问by atlantis
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.
我在网上查过这个,但我问这个是为了确保我没有错过任何东西。是否有内置函数将 HashSets 转换为 C# 中的列表?我需要避免元素重复,但我需要返回一个列表。
采纳答案by Graviton
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
.
根据定义,HashSet 不包含重复项。所以没有必要Distinct
。
回答by Simon Fox
There is the Linq extension method ToList<T>()
which will do that (It is defined on IEnumerable<T>
which is implemented by HashSet<T>
).
有一个 Linq 扩展方法ToList<T>()
可以做到这一点(它是在IEnumerable<T>
其上定义的,由 实现HashSet<T>
)。
Just make sure you are using System.Linq;
只要确保你是 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>
.
正如您显然知道的那样,这HashSet
将确保您没有重复项,并且此函数将允许您将其作为IList<T>
.
回答by Jon Skeet
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.
就我个人而言,我更喜欢打电话ToList
,这意味着您不需要重申列表的类型。
Contrary to my previous thoughts, both ways allow covariance to be easily expressed in C# 4:
与我之前的想法相反,这两种方式都可以在 C# 4 中轻松表达协方差:
HashSet<Banana> bananas = new HashSet<Banana>();
List<Fruit> fruit1 = bananas.ToList<Fruit>();
List<Fruit> fruit2 = new List<Fruit>(bananas);
回答by Jon Skeet
List<ListItemType> = new List<ListItemType>(hashSetCollection);