复杂字典的foreach循环不正确

时间:2012-03-23 11:13:53

标签: .net loops powershell dictionary

我正在使用Windows 7和PowerGUI脚本编辑器编写ps1。 这是我的代码的一部分:

#In global scope
$Type_Trans = "System.Collections.Generic.Dictionary[System.String,PSObject]"
$Type_Farms = "System.Collections.Generic.Dictionary[System.Int32,$Type_Trans]"

$Dic_Counts = New-Object $Type_Farms

#...puts some data in $Dic_Counts here...
#It is no problem with printing out it in console

#Now call the function below
Write-Data $Dic_Counts

Function Write-Data
{
    param(
        $Dic_Counts
    )

    Foreach($Dic_CountsSingle in $Dic_Counts)
    {
        Write-DataSingle $Dic_CountsSingle  #THIS LINE!
    }
}

这里很奇怪:为什么Dic_CountsSingle不是KeyValuePair,而是与Dic_Counts相同?

非常感谢!

3 个答案:

答案 0 :(得分:10)

使用

foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator())

PowerShell中的哈希表也是如此,所以并不特别令人惊讶。

答案 1 :(得分:7)

我这样做:

$Dic_Counts.keys | %{ $Dic_Counts[$_]  }

答案 2 :(得分:0)

我认为它在这里破裂了:

Foreach($Dic_CountsSingle in $Dic_Counts) 

那个foreach循环期待一个数组作为它的第二个参数。 $ Dic_Counts是一个哈希表,因此它没有索引。现在我想知道一个有序的哈希表是否可以在foreach循环中工作。它有一个索引。

不。 Foreach也不会枚举有序的哈希表。要自己做。