Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a HashSet to an ArrayList in PowerShell?

I need to convert a HashSet to an ArrayList?

$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?
like image 862
Daniel Avatar asked Oct 24 '18 06:10

Daniel


3 Answers

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
like image 59
marsze Avatar answered Sep 19 '22 13:09

marsze


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)
like image 25
Drew Avatar answered Sep 17 '22 13:09

Drew


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)
}
like image 21
Kirill Pashkov Avatar answered Sep 17 '22 13:09

Kirill Pashkov