Let's assume the following Dictonary:
$Grid = [System.Collections.Generic.Dictionary[[System.String],[System.Boolean]]]::new()
For ( $i = 0; $i -lt 10; $i ) {
For ( $j = 0; $j -lt 10; $j ) {
$Grid.Add("$i,$j", $false)
}
}
That makes a 10x10 "Grid" with some sort of Coordinates:
0,0 = False
0,1 = False
0,2 = False
and so on.
I am able to set a range of them to a specific value:
$Grid['0,0', '0,1', '0,2'] = $true
But i can't get it to work to toggle the actual value.
What i try to accomplish is something like
$Grid['0,0', '0,1', '0,2'] = -Not $_.Value
Any help is highly appreciated! - Thanks in advance!
CodePudding user response:
You'll have to access the entries individually:
'0,0', '0,1', '0,2' | ForEach-Object { $Grid[$_] = -not $Grid[$_] }
The reason is:
- Using multiple indices / keys using index notation (such as
['0,0', '0,1', '0,2']
) only works for getting elements / values, not also for setting.[1]
(Even if that worked, you wouldn't be able to refer to the target elements' / entries' existing value, and would therefore limit you to assigning the same, fixed value to all targets)
[1] As of PowerShell 7.2, while the error message in response to attempting such an assignment is explicit for arrays (assignment to slices is not supported.
, leaving aside that the term slices isn't really used in PowerShell), it is confusing for dictionaries (which includes hashtables): Unable to index into an object of type <dictionary-type>
. Similarly, attempting to assign to a property of a collection's elements via member enumeration - which isn't supported either - results in a confusing error message -see GitHub issue #5271.