[英]How create multidimensional dynamic array in powershell
How i can create array like: 我如何创建像这样的数组:
$a -> [1] ->
[1] = value1
[2] = value2
.................
[n] = valueN
[2] ->
[1] = value1
[2] = value2
.................
[n] = valueN
and so on. 等等。 Thank you 谢谢
i have tried like this: 我已经试过像这样:
$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
But it doesn't give the required output 但是它没有提供所需的输出
I think this has been posted multiple times, but simply declare the array and give it values: 我认为这已经发布了多次,但只需声明数组并为其赋值:
[array]$1 = "value1","value2"
[array]$2 = "value1","value2"
[array]$a = $1,$2
$a[0][0]
will output -> value1 from the first 从第一个输出-> value1
Please note that declaring the array with [array] is for clarifiying, it is not necessary. 请注意,使用[array]声明数组是为了澄清,没有必要。 If you add comma-seperated values the variable automatically is an array. 如果添加逗号分隔的值,则变量自动为数组。
EDIT: What you have tried is a hashtable. 编辑:您尝试过的是一个哈希表。 A hashtable contains a key and a value. 哈希表包含一个键和一个值。 An array is only a list of values. 数组只是值列表。 A hashtable is created as follows: 哈希表的创建如下:
$b = @{
1 = @{
1 = "value1"
2 = "value2"
}
2 = @{
1 = "value1"
2 = "value2"
}
3 = "value3"
}
$b
As you can see, you can add as many sublevels as you like. 如您所见,您可以根据需要添加任意多个子级别。 To show the value of the first "value1" type: 要显示第一个“ value1”的值,请输入:
$b[1].1
You could use the class approach as well I would prefer: 您也可以使用类方法,我更喜欢:
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
The Windows Powershell in Action answer. Windows Powershell在行动中的答案。
$2d = New-Object -TypeName 'object[,]' -ArgumentList 2,2
$2d.Rank
#2
$2d[0,0] = "a"
$2d[1,0] = 'b'
$2d[0,1] = 'c'
$2d[1,1] = 'd'
$2d[1,1]
#d
# slice
$2d[ (0,0) , (1,0) ]
#a
#b
# index variable
$one = 0,0
$two = 1,0
$pair = $one,$two
$2d[ $pair ]
#a
#b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.