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

时间:2018-10-24 06:11:11

标签: arrays list powershell 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?

3 个答案:

答案 0 :(得分:4)

不确定这是否是您要的东西,但是您可以...

$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)

答案 1 :(得分:3)

一种使用CopyTo的方式:

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

另一种方式(对于较大的哈希集,该方法更短,但是更慢):

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

此外,我强烈建议List胜过ArrayList,因为自引入泛型以来几乎deprecated

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

答案 2 :(得分:1)

您还可以使用hashtable循环将arrayforeach的每个项目添加:

$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)
}