PowerShell |优化搜索:预先知道只有一个唯一对的两个数组的元素之间的匹配



当我在两个数组(每个数组包含数千个元素(之间匹配元素时,我想优化流程。如果找到了匹配项,则我们转到下一个元素,而不是继续搜索另一个匹配项(因为每个元素都是唯一的,所以不存在(。

$array1 = @(thousandItemsForExample)
$array2 = @(thousandItemsForExample)
foreach ($array1item in $array1) {
$object = [PSCustomObject]@{
property1 = $array1item.property1
property2 = ($array1 | Where-Object { $_.property1 -eq $array2.property1 } | Select-Object property2).property2
}

我试着找出是否有任何比较运算符有这种选择,但我什么都找不到。

谢谢!:(

PS:对不起,我的英语不是我的母语。。。

您可以在哈希表的帮助下快速查找。此外,Group-Object -AsHashtable对哈希表的构建也有很大帮助:

$array1 = @(thousandItemsForExample)
$array2 = thousandItemsForExample | Group-Object property1 -AsHashTable -AsString
$result = foreach ($item in $array1) {
[PSCustomObject]@{
property1 = $item.property1
property2 = $array2[$item.property1].property2
}
}

创建一个哈希表,并将$array2中的所有项目加载到其中,使用property1的值作为关键字:

$array1 = @(thousandItemsForExample)
$array2 = @(thousandItemsForExample)
$lookupTable = @{}
$array2 |ForEach-Object {
$lookupTable[$_.property1] = $_
}

通过键从哈希表中提取相应的项目将比每次使用Where-Object过滤整个数组快得多:

foreach ($array1item in $array1) {
$object = [PSCustomObject]@{
property1 = $array1item.property1
property2 = $lookupTable[$array1item.property1].property2
}
}

最新更新