我如何在.NET中将一个HashSet<T>转换为数组?
使用HashSet<T>.CopyTo
方法。该方法将HashSet<T>
中的项目复制到数组中。
因此,给定名为stringSet
的HashSet<String>
,您可以按照以下方式进行操作:
String[] stringArray = new String[stringSet.Count];
stringSet.CopyTo(stringArray);
如果您指的是System.Collections.Generic.HashSet,那么有点困难,因为该类在3.5框架之前不存在。
如果您的意思是您正在使用3.5,则只需使用ToArray,因为HashSet实现了IEnumerable,例如:
using System.Linq;
...
HashSet<int> hs = ...
int[] entries = hs.ToArray();
如果你有自己的HashSet类,就很难说了。
我猜
function T[] ToArray<T>(ICollection<T> collection)
{
T[] result = new T[collection.Count];
int i = 0;
foreach(T val in collection)
{
result[i++] = val;
}
}
对于任何ICollection<T>
实现。
实际上,由于您必须引用System.Core
才能使用HashSet<T>
类,因此您可以使用它:
T[] myArray = System.Linq.Enumerable.ToArray(hashSet);
现在你可以更简单地实现它,使用List<T>
构造函数(列表是现代数组 :)。
例如,在PowerShell中:
$MyNewArray = [System.Collections.Generic.List[string]]::new($MySet)
HashSet<T>
只能在 .Net 3.5 中使用。因此,您可以使用ToArray()
Linq 扩展方法。 - adrianbanks