在PowerShell中的联合和交集?中,介绍了有关数组集合操作的酷炫一行代码。
我希望使用哈希表来实现这一点,并且已经找到了使用字典键集的解决方案。为了将其扩展到值,我使用for循环迭代键的交集并将值复制到新的结果哈希表中。但这看起来不够简洁。
进一步的研究显示,使用GetEnumerator也不够简洁。
我该如何用简洁而美观的一行代码替换臃肿的for循环或枚举器?
以下是源代码:
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 $_)}
# I don't 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 $_}