我有2个数组,每个数组有2个字段(例如'item'和'price')。
以下是我的1个数组的get-member结果(实际上两个数组都具有相同的结构)
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
item NoteProperty System.String field1=computer
price NoteProperty System.String field2=2000
我需要找到数组$ shopA中的项目,其中在$ shopB数组中找不到项目。我现在使用2个循环来查找缺少的项目。
$missing = @()
foreach ($itemA in $shopA) {
$found = 0
foreach ($itemB in $shopB) {
if ($itemB.item -eq $itemA.item) {
$found = 1
}
}
if ($found = 0) {
$missing += $itemA
}
}
这个方法适合我,但是我的2个数组非常大,我想要比通过整个数组循环更快的方法......
我一直在寻找一种更好的方法,而且compare-object几乎完成了这项工作,但所有的例子似乎只适用于单维数组。
由于
答案 0 :(得分:1)
从我所看到的,你确实有两个一维阵列,尽管你声称相反。
找到丢失物品的天真方式是
$missing = $shopA | ? { $x = $_; !($shopB | ? {$_.item -eq $x.item})}
但是,这总是O(n²);为了更快,你可以先从一个hastable中收集$shopB
中的所有项目,这样可以检查是否存在O(1),而不是O(n):
$hash = @{}
$shopB | %{ $hash[$_.item] = 1 }
$missing = $shopA | ?{ !$hash.ContainsKey($_.item) }
答案 1 :(得分:0)
这样的东西?
$shopA= @(1, 2, 3, 4)
$shopB= @(4, 3, 5, 6)
$shopB | where { $shopA -notcontains $_ }