2012-06-24 34 views
3

是否有一個函數,方法或語言結構允許從Powershell中的多維數組中檢索單個列?Powershell:如何從多維數組中獲取單個列?

$my_array = @() 
$my_array += ,@(1,2,3) 
$my_array += ,@(4,5,6) 
$my_array += ,@(7,8,9) 

# I currently use that, and I want to find a better way: 
foreach ($line in $my_array) { 
    [array]$single_column += $line[1] # fetch column 1 
} 
# now $single_column contains only 2 and 5 and 8 

我的最終目標是從一列中找到非重複的值。

回答

4

對不起,我不認爲這樣的事情存在。我會去:

@($my_array | foreach { $_[1] }) 

要快速找到獨特的價值我傾向於使用哈希表鍵破解:

$UniqueArray = @($my_array | foreach -Begin { 
    $unique = @{} 
} -Process { 
    $unique.($_[1]) = $null 
} -End { 
    $unique.Keys 
}) 

顯然,它有它的侷限性...

+0

謝謝!在看到您提交之前,我剛剛找到了相同的解決方案。對於第二部分...呃...我試圖找到一個更好的:) –

+0

在PowerShell中總是有很少的方法去皮膚貓。 :) – BartekB

1

要提取一列:

$single_column = $my_array | foreach { $_[1] } 

提取任何列:

$some_columns = $my_array | foreach { ,@($_[2],$_[1]) } # any order 

從一列發現非重複值:

$unique_array = $my_array | foreach {$_[1]} | sort-object -unique 
# caveat: the resulting array is sorted, 
# so BartekB have a better solution if sort is a problem