C#Dictionary按索引获取项目
我试图制作一个方法,从我的字典中随机返回一个名片。
我的字典:第一个定义卡的名称是字符串,第二个是该卡的值,即int。
public static Dictionary _dict = new Dictionary() { {"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); }
所以问题是:
cannot convert from 'int' to 'string'
有人帮我怎么做才能得到这个名字?
这将返回对应于随机生成的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
您可以为每个索引获取键或值:
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
你的密钥是一个字符串,你的值是一个int。 您的代码将无法正常工作,因为它无法查找您传递的随机内容。 另外,请提供完整的代码