Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary get item by index

I am trying to make a method that returns a name of a card from my Dictionary randomly.

My Dictionary: First defined name of the card which is string and second is the 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 a randomly generated int.

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

So the problem is:

Cannot convert from 'int' to 'string'

Anybody helps me how should I do it right to get the name?

like image 791
Jakub Staněk Avatar asked Nov 03 '16 22:11

Jakub Staněk


3 Answers

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

like image 113
Hadi Avatar answered Oct 11 '22 05:10

Hadi


You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1 string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1 
like image 43
mybirthname Avatar answered Oct 11 '22 05:10

mybirthname


you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

like image 27
Noorul Avatar answered Oct 11 '22 07:10

Noorul