我创建了一个字典,我希望用户写入城市(kommune),然后获取显示在名为 txtKommuneresultalt 的文本框中的值(procent)
\n\n我是 C# 新手,所以我希望有人能帮助我
\n\n我已经尝试搜索几天了,没有任何效果。我正在使用 Windowsforms,并且已准备好 ButtonHandler
\n\n到目前为止这是我的代码:
\n\nDictionary<double, string> dictionary = new Dictionary<double, string>();\ndouble procent = Convert.ToDouble(txtKommuneresultat.Text);\nstring kommune = txtKommuneInput.Text;\n\n\ndictionary.Add(11.44, "Faxe");\ndictionary.Add(4.29, "Greve");\ndictionary.Add(7.11, "Gulborgsund");\ndictionary.Add(7.86, " Holb\xc3\xa6k");\ndictionary.Add(5.67, "Kalundborg");\ndictionary.Add(4.99, "K\xc3\xb8ge");\ndictionary.Add(7.28, "Lejre");\ndictionary.Add(2.67, "Lolland");\ndictionary.Add(4.07, "N\xc3\xa6stved");\ndictionary.Add(1.21, "Odsherred");\ndictionary.Add(5.02, "Ringsted");\ndictionary.Add(13.23, "Slagelse");\ndictionary.Add(20.75, "Solr\xc3\xb8d");\ndictionary.Add(1.81, "Sor\xc3\xb8");\ndictionary.Add(5.50, "Stevns");\ndictionary.Add(1.29, "Vordingborg");\n\ntxtKommuneresultat.Show();\nRun Code Online (Sandbox Code Playgroud)\n
字典中的第一个类型是键,第二个类型是值。字典允许您根据值的key查找值。
目前,您将 adouble作为第一种类型(键),将 astring作为第二种类型(值)。string这将允许您使用double值作为键来查找值。
可是等等。双精度数代表百分比,而字符串代表城市名称。您想要根据城市名称查找百分比。所以string应该是你字典中的键,而不是 double。
Dictionary<string, double> dictionary = new Dictionary<string, double>();
Run Code Online (Sandbox Code Playgroud)
这允许您通过提供正确的字符串来获取特定的双精度值:
var percentage = dictionary["Gulborgsund"];
Run Code Online (Sandbox Code Playgroud)
由于查找将基于用户输入(通常不可靠),因此最好使用以下TryGetValue方法:
double percentage;
if (dictionary.TryGetValue(userInput, out percentage))
{
// Use percentage
}
else
{
// Could not retrieve value
}
Run Code Online (Sandbox Code Playgroud)