开发者

How to lookup a multi-value Name in a hashtable?

If I have a hashtable with a multi-value Name, how do I specify the Name when I do a lookup?

Here are some contrived examples ...

$unary = @{
    $false, "!A";
    $true,  "A"
}

$unary
Name                           Value
----                           -----
False                       开发者_C百科   !A
True                           A

$unary[$false]
!A
$unary[$true]
A

So far so good.

$binary = @{
  ($false, $false) = "!A and !B"
  ($false, $true)  = "!A and B"
  ($true,  $false) = "A and !B"
  ($true,  $true)  = "A and B"
}

$binary
Name                           Value
----                           -----
{False, True}                  !A and B
{True, False}                  A and !B
{True, True}                   A and B
{False, False}                 !A and !B

$binary[$false, $true]
//Nothing
$binary[($false, $true)]
//Nothing
$binary[{$false, $true}]
//Nothing
//www.stackoverflow.com... :)

What do I need to specify in $binary[...] to get a value?


Your problem is that you are using arrays as keys in a hash table. Just to illustrate what goes wrong here:

PS Home:\> $x=$false,$false
PS Home:\> $y=@($binary.Keys)[0]
PS Home:\> $x
False
False
PS Home:\> $y
False
False
PS Home:\> $x.Equals($y)
False

Both objects also have different hashcodes. They won't ever be a good idea to use as keys in hash tables, as you cannot extract the values again, unless using the exact same references you put into the hash table.

The easier eay would probably be to use a single object as key:

$binary = @{
  0 = "!A and !B"
  1  = "!A and B"
  10 = "A and !B"
  11  = "A and B"
}

or similar. Then extracting

$binary[01]

will yield "!A and B" as expected.

Note also that a List will have the same problem with equality. Tuples might work, but those aren't available in .NET 2.


Here is a not so honnest solution, but depending on what you want to do it can help.

$unary = new-object ‘object[]’ 2
$unary[$false] = "!A"
$unary[$true] = "A"

$binary= new-object ‘object[,]’ 2,2
$binary[$false,$false] = "!A and !B"
$binary[$false,$true] = "!A and B"
$binary[$true,$false] = "A and !B"
$binary[$true,$true] = "A and B"

Result :

PS > $binary[$true,$true]
A and B


Probably not what you wanted to see, but:

$binary = @{
  [string]($false,$true)  = "!A and B"
  [string]($true,$false) = "A and !B"
  [string]($true,$true)  = "A and B"
}

$binary[[string]($false,$true)]


!A and B
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜