Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare element values between two Ordered Dictionaries

Tags:

c#

I am trying to compare the values in the elements of two ordered dictionaries. I am unable to find the right coding to get at the elements at index 0 and convert them into DictionaryEntrys. I am trying to use the following code:

DictionaryEntry card1 = (DictionaryEntry)(player1.Hand[0]); 
DictionaryEntry card2 = (DictionaryEntry)(player2.Hand[0]);


if ((int)card1.Value > (int)card2.Value)
{
    // do stuff
}

The code passes intellisense, but blows up with an invalid cast. I can also code

 var card1 = player1.Hand[0];

but it won't allow me to retrieve card1.Value. So far as I can tell, card1 needs to be converted to a DictionaryEntry, and I don't know how to do it.

Any help would be much appreciated. Thanks.

like image 592
Pismotality Avatar asked Nov 17 '25 18:11

Pismotality


2 Answers

The indexer in OrderedDictionary is implemented as follows:

public object this[int index]
{
    get { return ((DictionaryEntry)objectsArray[index]).Value; }
    set { ... }
}

It's returning the value, not the key/value pair. That's why you can't cast it to a DictionaryEntry.

Do your comparison like this instead, casting the return value of the indexer directly to int:

if ((int)player1.Hand[0] > (int)player2.Hand[0])
{
    // do stuff
}

From your comment, it sounds like you want to be able to modify the key too.

AFAIK, you'll have to use the key or index to get the value, then remove the old element and add/insert the new one:

 var value = (int)player1.Hand[0];
 player1.Hand.RemoveAt(0);
 player1.Hand.Add("someNewKey", value);

 var value = (int)player1.Hand["oldKey"];
 player1.Hand.Remove("oldKey");
 player1.Hand.Add("someNewKey", value);
like image 199
Grant Winney Avatar answered Nov 20 '25 06:11

Grant Winney


I found this in another thread, which helped me get at both key and value in the Ordered Dictionary:

DictionaryEntry card1 = player1.Hand.Cast<DictionaryEntry>().ElementAt(0);

thus card1.Key == key and card1.Value == value

like image 35
Pismotality Avatar answered Nov 20 '25 07:11

Pismotality



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!