如何在PowerShell中将HashSet转换为ArrayList?

Dan*_*iel 5 arrays powershell list arraylist

我需要将HashSet转换为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?
Run Code Online (Sandbox Code Playgroud)

mar*_*sze 5

一种方法,使用CopyTo

$array = New-Object int[] $hashset.Count
$hashset.CopyTo($array)
$arraylist = [System.Collections.ArrayList]$array
Run Code Online (Sandbox Code Playgroud)

另一种方式(更短,但对于大型哈希集更慢):

$arraylist = [System.Collections.ArrayList]@($hashset)
Run Code Online (Sandbox Code Playgroud)

此外,我强烈建议使用Listover ArrayList,因为自从引入泛型以来,它几乎已被弃用

$list = [System.Collections.Generic.List[int]]$hashset
Run Code Online (Sandbox Code Playgroud)