Reputation: 3511
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?
Upvotes: 11
Views: 3372
Reputation: 4020
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)
Upvotes: 5
Reputation: 17055
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
Upvotes: 7
Reputation: 3236
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)
}
Upvotes: 1