将 HashSet<T> 转换为 .NET 中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1603650/
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
Convert a HashSet<T> to an array in .NET
提问by Agnel Kurian
How do I convert a HashSet<T> to an array in .NET?
如何将 HashSet<T> 转换为 .NET 中的数组?
回答by Andrew Hare
Use the HashSet<T>.CopyTomethod. This method copies the items from the HashSet<T>to an array.
使用HashSet<T>.CopyTo方法。此方法将项目从 复制HashSet<T>到数组。
So given a HashSet<String>called stringSetyou would do something like this:
所以给定一个HashSet<String>电话,stringSet你会做这样的事情:
String[] stringArray = new String[stringSet.Count];
stringSet.CopyTo(stringArray);
回答by erikkallen
If you mean System.Collections.Generic.HashSet, it's kind of hard since that class does not exist prior to framework 3.5.
如果您的意思是 System.Collections.Generic.HashSet,那有点困难,因为该类在框架 3.5 之前不存在。
If you mean you're on 3.5, just use ToArray since HashSet implements IEnumerable, e.g.
如果你的意思是你在 3.5 上,只需使用 ToArray,因为 HashSet 实现了 IEnumerable,例如
using System.Linq;
...
HashSet<int> hs = ...
int[] entries = hs.ToArray();
If you have your own HashSet class, it's hard to say.
如果你有自己的 HashSet 类,那就很难说了。
回答by Max
Now you can do it even simpler, with List<T>constructor (Lists are modern Arrays :).
E. g., in PowerShell:
现在你可以更简单地使用List<T>构造函数(列表是现代数组:)。例如,在 PowerShell 中:
$MyNewArray = [System.Collections.Generic.List[string]]::new($MySet)
回答by Julien Roncaglia
I guess
我猜
function T[] ToArray<T>(ICollection<T> collection)
{
T[] result = new T[collection.Count];
int i = 0;
foreach(T val in collection)
{
result[i++] = val;
}
}
as for any ICollection<T>implementation.
至于任何ICollection<T>实现。
Actually in fact as you must reference System.Coreto use the HashSet<T>class you might as well use it :
实际上,实际上因为您必须引用System.Core才能使用HashSet<T>该类,您也可以使用它:
T[] myArray = System.Linq.Enumerable.ToArray(hashSet);

