C# Dictionary get item by index

Jakub Staněk picture Jakub Staněk · Nov 3, 2016 · Viewed 119.7k times · Source

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

Hadi picture Hadi · Nov 3, 2016

If you need to extract an element key based on index, this function can be used:

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

If you need to extract the Key where the element value is equal to the integer generated randomly, you can used the following function:

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

Side Note: The first element of the dictionary is The Key and the second is the Value