How to compare element values ​​between two ordered dictionaries

I am trying to compare values ​​in the elements of two ordered dictionaries. I cannot find the correct encoding to get the elements at index 0 and convert them to 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 explodes with an invalid litas. I can also code

 var card1 = player1.Hand[0];

      

but it won't let me get card1.Value. As far as I can tell, card1 needs to be converted to DictionaryEntry and I don't know how to do that.

Any help would be much appreciated. Thank.

+3


source to share


2 answers


I found this on another thread that helped me get both key and value in an ordered dictionary:

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

      



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

+1


source


The indexer in OrderedDictionary

is implemented as follows:

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

      

Returns a value, not a key / value pair. This is why you cannot transfer it to DictionaryEntry

.

Do a comparison instead, returning the return value of the indexer directly to int

:



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

      

From your comment, it looks like you want to change the key.

AFAIK, you will need to use the key or index to get the value, then remove the old element and add / insert a 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);

      

+6


source







All Articles