Jakub Staněk Jakub Staněk - 1 year ago 173
C# Question

C# Dictionary get item by index

im trying to make a method which return a name of card from my Dictionary
randomly.

My Dictionary: First definied name of card which is string and second is value of that card, which is int.

public static Dictionary<string, int> _dict = new Dictionary<string, int>()
{
{"7", 7 },
{"8", 8 },
{"9", 9 },
{"10", 10 },
{"J", 1 },
{"Q", 1 },
{"K", 2 },
{"A", 11 }
};


Method:
random is random generated int.

public string getCard(int random)
{
return Karta._dict(random);
}


So the problem is:

cannot convert from 'int' to 'string'


Anybody help me how should i do it right to get the name?

Answer Source

Just use the following code:

   public string getCard(int random)
{
    return Karta._dict.FirstOrDefault(x => x.Value == random).Key;
}

This will Return the Key of corresponding to the int Value generated randomly

   public string getCard(int random)
{
    return Karta._dict.ElementAt(random).Key;
}

This will Return the Key of corresponding to the int Index generated randomly

The first element of the dictionary is The Key and the second is the Value

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download