C#Dictionary按索引获取项目

问题描述 投票:22回答:3

我试图制作一个方法,从我的字典中随机返回一个名片。

我的词典:第一个定义卡的名称是字符串,第二个是该卡的值,即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 }
    };

方法:随机随机生成int。

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

所以问题是:

无法从'int'转换为'string'

有人帮我怎么做才能得到这个名字?

c# dictionary
3个回答
25
投票

这将返回对应于随机生成的int值的Key

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

这将返回对应于随机生成的int索引的Key

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

侧注:字典的第一个元素是The Key,第二个是Value


24
投票

您可以为每个索引获取键或值:

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

2
投票

你的密钥是一个字符串,你的值是一个int。您的代码无法正常工作,因为它无法查找您传递的随机内容。另外,请提供完整的代码

© www.soinside.com 2019 - 2024. All rights reserved.