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?
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
IEnumerable[int] (including HashSet[int]) directly as its argument, faster than casting it: [System.Collections.Generic.List[int]]::new($hashset)@() in my answer, it's unnecessary, as you correctly stated. Another nice benefit of using List instead of ArrayList! Then you can just do the cast and it will be about the same speed is it's (most likely) using the constructor internally.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)
}
Sort().GetRange()which also isn't supported by the Array thatSort-Objectreturns.