C# Dictionary get item by index

If you need to extract an element key based on an 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 use the following function:

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

Make sure that you added reference to System.Linq in your class.

using System.Linq;

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

Leave a Comment