如何转换HashSet< T>到.NET中的数组?

有帮助吗?

解决方案

使用 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&lt; T&gt; 实施。

实际上你必须引用 System.Core 来使用 HashSet&lt; T&gt; 类,你也可以使用它:

T[] myArray = System.Linq.Enumerable.ToArray(hashSet);

现在你可以更简单地使用 List&lt; T&gt; 构造函数(列表是现代数组:)。 例如,在PowerShell中:

$MyNewArray = [System.Collections.Generic.List[string]]::new($MySet)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top