例如
$people = @(
@('adam', '24', 'M')
@('andy', '20', 'M')
@('alex', '30', 'M')
@('ava', '25', 'F')
)
foreach($person in $people | where ($person[1] -lt '25') -and ($person[2] -eq 'M'))
這應該選擇adam和andy...
uj5u.com熱心網友回復:
您應該為您的Where-Object陳述句使用的語法是:
$people = @(
@('adam', '24', 'M'),
@('andy', '20', 'M'),
@('alex', '30', 'M'),
@('ava', '25', 'F')
)
$people | Where-Object { $_[1] -lt '25' -and $_[2] -eq 'M' } | ForEach-Object { $_[0] }
# Results in:
#
# adam
# andy
或者使用帶有陳述句的傳統foreach回圈:if
foreach($array in $people) {
if($array[1] -lt 25 -and $array[2] -eq 'M') {
$array[0]
}
}
但是,正如先前答案中所建議的那樣,哈希表可能更適合于此(即使語法有點復雜):
$people = @{
M = @{
24 = 'adam'
20 = 'andy'
30 = 'alex'
}
F = @{
25 = 'ava'
}
}
$people['M'][$people['M'].Keys -lt 25]
uj5u.com熱心網友回復:
圣地亞哥的有用答案很好地解決了您的問題。
讓我提供一個替代方案,它使用 PowerShell v5 自定義class來為您的陣列實體建模,這使得對每個人的屬性的訪問更具描述性和型別安全:
# Define a [Person] class with a constructor that fills all properties.
class Person {
[string] $Name
[int] $Age
[char] $Sex
Person([string] $name, [int] $age, [char] $sex) {
$this.Name = $name; $this.Age = $age; $this.Sex = $sex
}
}
# Create an array of [Person] instances.
$people = @(
[Person]::new('adam', '24', 'M')
[Person]::new('andy', '20', 'M')
[Person]::new('alex', '30', 'M')
[Person]::new('ava', '25', 'F')
)
# Filter the array via the .Where() array method.
$people.Where({ $_.Age -lt 25 -and $_.Sex -eq 'M' })
輸出:
Name Age Sex
---- --- ---
adam 24 M
andy 20 M
如果您只對.Name屬性值感興趣,只需附加.Name到上面的最后一個命令,該命令回傳 array 'adam', 'andy',由 PowerShell 的成員訪問列舉功能提供。
請注意.Where()陣列方法Where-Object的使用,對于已經在記憶體中的集合,它是cmdlet的更有效替代方法;也就是說,foreach陳述句表現最好。
uj5u.com熱心網友回復:
您當然可以使用涉及 ForEach-Object 的答案。唯一可能的問題(取決于您嘗試使用該資料做什么)是ForEach-Object將單獨執行每條資料記錄。
另一種方法是創建您想要的物件,然后使用標準的 foreach()。
$people = @(
@('adam', '24', 'M')
@('andy', '20', 'M')
@('alex', '30', 'M')
@('ava', '25', 'F')
)
$filteredPeople = $people | Where-Object { $_[1] -lt '25' -and $_[2] -eq 'M'}
foreach($person in $$filteredPeople) {
#stuff
}
這將對整個物件執行相同的功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478641.html
標籤:电源外壳
