gpt4 book ai didi

C# 字典按索引获取项目

转载 作者:IT王子 更新时间:2023-10-29 04:20:36 25 4
gpt4 key购买 nike

我正在尝试创建一个方法,从我的字典中返回一张卡片的名称随机。

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

方法:random 是一个随机生成的 int。

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

所以问题是:

Cannot convert from 'int' to 'string'

谁能帮助我如何正确获取名称?

最佳答案

如果需要根据索引提取元素key,可以使用这个函数:

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

如果需要提取元素值等于随机生成的整数的Key,可以使用如下函数:

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

确保您在类中添加了对 System.Linq 的引用。

using System.Linq;

旁注:字典的第一个元素是键,第二个元素是值

关于C# 字典按索引获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com