Powershell中的哈希表的联合和交集

问题描述:

Union and Intersection in Powershell?中描述了用于设置数组的操作的超酷单线程。Powershell中的哈希表的联合和交集

我想用哈希表做这件事,并有一个使用字典的键集的解决方案。为了扩展到值,我使用for循环遍历键的交集并将值复制到新的结果哈希表。这看起来不干净。

进一步的研究表明,解决方案与GetEnumerator这也是不干净恕我直言。

我该如何用简洁和漂亮的单行条来替换臃肿的循环或枚举?

源代码如下:

http://paste.ubuntu.com/13362425/

# import csv 
$a = Import-Csv -Path A.csv -Delimiter ";" -Header "Keys","Values" 
$b = Import-Csv -Path B.csv -Delimiter ";" -Header "Keys","Values" 

# make nice hashtables for further use 
$AData = @{} 
foreach($r in $a) 
    { $AData[$r.Keys] = $r.Values } 
$BData = @{} 
foreach($r in $b) 
    { $BData[$r.Keys] = $r.Values } 

# set difference to find missing entries 
$MissingA = $AData.Keys | ?{-not ($BData.Keys -contains $_)} 

# dont know how to do set-operations on hashtables yet. so use keysets and copy data. (lame!) 
$MissingAData = @{} 
foreach($k in $MissingA) 
{ 
    $MissingAData[$k] = $AData[$k] 
} 

#intersection 
$Common = $AData.Keys | ?{$BData.Keys -contains $_} 
+0

你只能在“价值”或整个键值对有兴趣吗? –

+0

整个关键值对 – Bastl

您可以使用相同的技术为列表,但使用哈希表的键,当你在OP表示。

对于联合和交叉点,您有一个额外的问题。两个哈希表之间通用的键之间,你会保留哪个值?假设您将始终将值保留在第一个哈希表中。然后:

# need clone to prevent .NET exception of changing hash while iterating through it 
$h1clone = $hash1.clone() 

# intersection 
$h1clone.keys | ? {$_ -notin $hash2.keys} | % {$hash1.remove($_)} 

# difference: $hash1 - $hash2 
$h1clone.keys | ? {$_ -in $hash2.keys} | % {$hash1.remove($_)} 

# union. Clone not needed because not iterating $hash1 
$hash2.keys | ? {$_ -notin $hash1.keys} | % {$hash1[$_] = $hash2[$_]} 

或者你也可以这样做避免了克隆,并创建一个新的哈希表

# intersection 
$newHash = @{}; $hash1.keys | ? {$_ -in $hash2.keys} | % {$newHash[$_] = $hash1[$_]} 

# difference: $hash1 - $hash2 
$newHash = @{}; $hash1.keys | ? {$_ -notin $hash2.keys} | % {$newHash[$_] = $hash1[$_]} 
+0

的作品像一个魅力,感谢有关值问题的笔记保持交集。 – Bastl