注意:Bill Stewart's answer 最有效地回答了所提出的问题 - 创建值对的 列表,不考虑重复项。
此答案侧重于基于哈希表的解决方案,该解决方案在单个条目中收集给定品牌的所有模型,并允许按品牌高效查找模型。
您仍然可以使用哈希表 - 使用它方便的基于键的查找 - 如果您将与给定品牌关联的所有模型存储为 array每个品牌 - 根据定义是唯一的 - 条目:
# Note the duplicate 'VW' entry at the end.
$makes = 'Ferrari', 'Ford', 'VW', 'Peugeot', 'Subaru', 'VW'
# Corresponding models.
$models = 'Enzo', 'Focus', 'Golf', '206', 'Impreza', 'Polo'
$table = [ordered] @{}; $i=0 # [ordered] (PSv3+) preserves the order of the keys
foreach($make in $makes) {
# Add the model at hand to the make's array of models.
# The entry is created on demand as an array, due to [array]
# (which creates an [object[]] array),
# and for additional models the array is appended to.
# You could also use [string[]], specifically.
[array] $table[$make] += $models[$i++]
}
# Output the resulting hashtable
$table
这会产生:
Name Value
---- -----
Ferrari {Enzo}
Ford {Focus}
VW {Golf, Polo}
Peugeot {206}
Subaru {Impreza}
注意VW 的值有2 个条目({...} 表示一个值是一个数组)。
稍后要获取给定品牌的模型,只需使用:
$vwModels = $table['VW']
检查给定的品牌/型号对是否已包含在表中:
$table[$make] -contains $model