How to convert a HashSet to an ArrayList in PowerShell? How to convert a HashSet to an ArrayList in PowerShell? powershell powershell

How to convert a HashSet to an ArrayList in PowerShell?


One way, using CopyTo:

$array = New-Object int[] $hashset.Count$hashset.CopyTo($array)$arraylist = [System.Collections.ArrayList]$array

Another way (shorter, but slower for large hashsets):

$arraylist = [System.Collections.ArrayList]@($hashset)

Also, I strongly recommend to favor List over ArrayList, as it's pretty much deprecated since the introduction of generics:

$list = [System.Collections.Generic.List[int]]$hashset


Unsure if this is what you are after but it here you go...

$hashset = New-Object System.Collections.Generic.HashSet[int]$null = $hashset.Add(1)$null = $hashset.Add(2)$null = $hashset.Add(3)# @($hashset) converts the hashset to an array which is then # converted to an arraylist and assigned to a variable$ArrayList = [System.Collections.ArrayList]@($hashset)


You can also add every item from hashtable to array using foreach loop:

$hashset = New-Object System.Collections.Generic.HashSet[int]$hashset.Add(1)$hashset.Add(2)$hashset.Add(3)$arraylist = New-Object System.Collections.ArrayList# Now what?foreach ($item in $hashset){    $arraylist.Add($item)}