我如何创建像这样的数组:
$a -> [1] ->
[1] = value1
[2] = value2
.................
[n] = valueN
[2] ->
[1] = value1
[2] = value2
.................
[n] = valueN
,依此类推。 谢谢
我尝试过这样:
$b = @{}
$b[0][0] = 1
$b[0][1] = 2
$b[0][2] = 3
$b[1][0] = 4
$b[1][1] = 5
$b[1][2] = 6
$b
但是它没有提供所需的输出
答案 0 :(得分:1)
我认为这已经发布了很多次,但只需声明数组并为其赋值:
[array]$1 = "value1","value2"
[array]$2 = "value1","value2"
[array]$a = $1,$2
$a[0][0]
将从第一个输出-> value1
请注意,使用[array]声明数组是为了澄清,没有必要。如果添加逗号分隔的值,则变量将自动为数组。
编辑: 您尝试过的是一个哈希表。哈希表包含一个键和一个值。数组只是值列表。哈希表的创建如下:
$b = @{
1 = @{
1 = "value1"
2 = "value2"
}
2 = @{
1 = "value1"
2 = "value2"
}
3 = "value3"
}
$b
如您所见,您可以添加任意多个子级别。要显示第一个“ value1”的值,请输入:
$b[1].1
答案 1 :(得分:0)
您也可以使用类方法,我更喜欢:
Add-Type -AssemblyName System.Collections
# Create class with needed members
class myListObject {
[int]$myIndex
[System.Collections.Generic.List[string]]$myValue = @()
}
# generic list of class
[System.Collections.Generic.List[myListObject]]$myList = @()
#create and add objects to generic list
$myObject = [myListObject]::new()
$myObject.myIndex = 1
$myObject.myValue = @( 'value1', 'value2' )
$myList.Add( $myObject )
$myObject = [myListObject]::new()
$myObject.myIndex = 2
$myObject.myValue = @( 'value3', 'value4' )
$myList.Add( $myObject )
# search items
$myList | Where-Object { $_.myIndex -eq 1 } | Select-Object -Property myValue
$myList | Where-Object { $_.myValue.Contains('value3') } | Select-Object -Property myIndex
答案 2 :(得分:0)
运行中的Windows Powershell答案。
to_list1: 2.211 s
to_list2: 6.629 s