2012-05-23 31 views
0

我有2個數組,每個數組有2個字段(例如'item'和'price')。在Powershell 2D陣列中查找缺失的行

以下是我的陣列(實際上是兩個數組具有相同的結構)

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  

我需要找到的物品中找不到陣列$雪巴​​的項目1到Get-Member導致數組$ 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個陣列是相當大的,我想比循環整個數組直通更快的方法...

我一直在尋找更好的方法來做到這一點和比較對象幾乎可以完成這項工作,但所有的例子似乎只適用於單維數組。

謝謝

回答

1

從我能看到你有兩個1D陣列,儘管你聲稱相反。

尋找遺失物品的幼稚的方法是

$missing = $shopA | ? { $x = $_; !($shopB | ? {$_.item -eq $x.item})} 

然而,這將始終是O(N²);使人們更快,你可以收集$shopB所有項目在hastable第一,這使得檢查存在的O(1),而不是爲O(n):

$hash = @{} 
$shopB | %{ $hash[$_.item] = 1 } 
$missing = $shopA | ?{ !$hash.ContainsKey($_.item) } 
+0

謝謝喬伊。我想知道如果我可以解決這個問題而不用建立另一個散列表,但如果這是最好的方法,那麼我將創建一個散列表。 –

+0

您提到大數組,因此從性能的角度來看,您應該創建用於檢查存在性的散列表。 – Joey

+0

如果我需要創建一個新表,我還會嘗試使用compare-object。非常感謝,您的建議非常有幫助。 –

0

是這樣的?

$shopA= @(1, 2, 3, 4) 
$shopB= @(4, 3, 5, 6) 
$shopB | where { $shopA -notcontains $_ } 
+0

謝謝大衛。如果數組是二維的呢?我已經用我的數據嘗試了您的建議,但沒有奏效。 –

+1

請注意,他們的項目具有屬性,因此正常的相等可能不會直接工作。 – Joey