How do I Add variables to a KeyValuePair list?

So I noticed for some reason when trying to add variables into a list with the keyvaluepair attribute on it it gives the option for Add but then says that it doesn’t support Add. Whats a solution around this?

   List<KeyValuePair<int, string>> highscoreList = new List<KeyValuePair<int, string>>();
    void start()
    {
         highscoreList.Add(0, "empty");
    }

NoDumbQuestion has a good point to create an object for this, but if you other reasons for using KeyValuePair, here’s the missing part for making that work:


highscoreList.Add( new KeyValuePair< int, string >( 0, "empty" ) );

The reason this is required is simply that the type for List is KeyValuePair, not two different types of int and string. Add requires a KeyValuePair< int, string >, and the point here is that the type being created out of the generic class KeyValuePair incorporates the two parameter types int and string (put another way, the type is a combination of all 3 components).


Making a struct or class to hold the data allows for something similar as NoDumbQuestion points out, but you still have the same basic issue, that Add would require a new Data( 0, “empty”). Where that may be uncomfortable to repeat, you must consider making a member method to perform the addition for you so you can merely supply the parameters as you’ve written (which seems more convenient), as in:

 void start()
 {
      addHighScore(0, "empty");
 }

void addHighScore( int s, string n )
{
 highscoreList.Add( new KeyValuePair< int, string >( s, n ) );
}