Pregunta

¿Cómo convierto un HashSet < T > a una matriz en .NET?

¿Fue útil?

Solución

Use el HashSet < T > .CopyTo método. Este método copia los elementos del HashSet < T > a una matriz.

Entonces, dado un HashSet < String > llamado stringSet , harías algo como esto:

String[] stringArray = new String[stringSet.Count];
stringSet.CopyTo(stringArray);

Otros consejos

Si te refieres a System.Collections.Generic.HashSet, es un poco difícil ya que esa clase no existe antes del marco 3.5.

Si te refieres a que estás en la versión 3.5, solo usa ToArray ya que HashSet implementa IEnumerable, por ejemplo

using System.Linq;
...
HashSet<int> hs = ...
int[] entries = hs.ToArray();

Si tienes tu propia clase HashSet, es difícil de decir.

Supongo

function T[] ToArray<T>(ICollection<T> collection)
{
    T[] result = new T[collection.Count];
    int i = 0;
    foreach(T val in collection)
    {
        result[i++] = val;
    }
}

como para cualquier implementación de ICollection < T > .

De hecho, como debe hacer referencia a System.Core para usar la clase HashSet < T > , también puede usarla:

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

Ahora puede hacerlo aún más simple, con el constructor List < T > (las listas son arrays modernos :). E. g., En PowerShell:

$MyNewArray = [System.Collections.Generic.List[string]]::new($MySet)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top