希望能够快速访问复杂的数据,并且我希望将它们组织成哈希数组的散列。
我有点不确定哈希看起来类似于数组:我如何以安全的方式定义它?
备注:我首先想到的是,如果哈希的简单散列但是鞋子的所有特征都不是个体的,并且可能导致键碰撞,所以我开始考虑最相关特征的数组。
1)'外部'键是[string] item-names(鞋名),
2)然后我想要一组[单个]数字(如鞋子大小)和
3)'落后'数组中的每个数字我都需要一个哈希,其中包含这款鞋子的更多细节:@ {"颜色" ="白色&#34 ;; "材料" ="皮革和#34 ;; ...}
这样我就可以轻松滚动:
$item = @{
"Shoe1 = @() # an array of sizes of that shoe-name
"Shoe2 = @() # an array of sizes of that shoe-name
}
所以$ item.Shoe1应该是它的大小数组:
foreach($size in $item.Shoe1) {
if ( $size -gt 10.5 -or $size -lt 10.0 ) { continue }
# how do I access the hash behind the size = an indiv. shoe?
if($size.Color -eq 'white') {...}
}
a)你会建议另一种方式吗?
b)如何定义这种结构?
c)我如何添加一个大小的哈希'背后'去鞋子?
提前致谢! Gooly
答案 0 :(得分:1)
(根据6/20评论修改完整答案)
根据你的反馈@gooly并重新阅读你的问题,我正在擦洗我的整个答案,给你一些对你更有用的东西。 你是正确的,哈希数组的散列将起作用,如第一个例子。请注意,6号便鞋有3种不同颜色/材质组合:
$shoeDictionary = @{
Loafer = @(
@{ Size = 6; Color = "White"; Material = "Leather" },
@{ Size = 6; Color = "Brown"; Material = "Faux Leather" },
@{ Size = 6; Color = "Blue"; Material = "Leather" },
@{ Size = 10.5; Color = "Black"; Material = "Patent Leather" }
)
Oxford = @(
@{ Size = 5; Color = "Blue"; Material = "Leather" },
@{ Size = 5.5; Color = "Green"; Material = "Faux Leather" }
)
}
当您要求白色尺寸6时,根本不需要任何环路:
PS> $shoeDictionary.Loafer | Where { $_.Size -eq 6 -and $_.Color -eq "White" }
Name Value
---- -----
Color White
Material Leather
Size 6
但是考虑一个更广泛的问题:向我展示尺码为6的所有便鞋,你得到这个:
PS> $shoeDictionary.Loafer | Where Size -eq 6
Name Value
---- -----
Color White
Material Leather
Size 6
Color Brown
Material Faux Leather
Size 6
Color Blue
Material Leather
Size 6
......这不是非常清晰。一个更好的选择是根据对象而不是哈希来思考,即对象的数组的哈希,而不是哈希的数组的哈希,以及:
$shoeDictionary = @{
Loafer = @(
(New-Object PSObject -Property @{ Size = 6; Color = "White"; Material = "Leather" }),
(New-Object PSObject -Property @{ Size = 6; Color = "Brown"; Material = "Faux Leather" }),
(New-Object PSObject -Property @{ Size = 6; Color = "Blue"; Material = "Leather" }),
(New-Object PSObject -Property @{ Size = 10.5; Color = "Black"; Material = "Patent Leather" })
)
Oxford = @(
(New-Object PSObject -Property @{ Size = 5; Color = "Blue"; Material = "Leather" }),
(New-Object PSObject -Property @{ Size = 5.5; Color = "Green"; Material = "Faux Leather" })
)
}
现在,当你看到所有6号便鞋时,你会得到更加可口的结果:
PS> $shoeDictionary.Loafer | Where Size -eq 6
Color Material Size
----- -------- ----
White Leather 6
Brown Faux Leather 6
Blue Leather 6