【发布时间】:2018-06-07 12:54:19
【问题描述】:
我正在尝试用 C# 编写一些代码,以便在提供以下输入后访问下表中的值:
地面(岩石、硬土、软土)
矩量级(6.5、7.5、8.5)
source_to_source (0-20, 20-50, 50-100)
我已尝试使用以下代码,但不断收到消息:
System.Collections.Generic.KeyNotFoundException 发生 - “字典中不存在给定的键”。
谁能帮我让它工作?有没有更有效的方式来编写这段代码?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20180607_dict_example1
{
class Program
{
static void Main(string[] args)
{
string ground = "Rock";
string moment_magnitude = "6.5";
string source_to_source = "0-20";
double ratio_peak;
int first_value;
int second_value;
int third_value;
// 0b. Calculate ratio peak from Table 2 in Hashash paper
var valueDict = new Dictionary<string, int> { { "6.5", 0 }, { "7.5", 1 }, { "8.5", 2 }, { "rock", 0 }, { "stiff soil", 1 }, { "soft soil", 2 }, };
if (valueDict.ContainsKey(moment_magnitude))
{
first_value = valueDict[moment_magnitude];
Console.WriteLine(first_value);
}
if (valueDict.ContainsKey(ground))
{
second_value = valueDict[ground];
Console.WriteLine(second_value);
}
int[,] array = new int[3, 3] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
Console.WriteLine(array[valueDict[ground], valueDict[moment_magnitude]]);
var valueDict_source_to_source = new Dictionary<string, int> { { "0-20", 0 }, { "20-50", 1 }, { "50-100", 2 } };
if (valueDict_source_to_source.ContainsKey(source_to_source))
{
third_value = valueDict_source_to_source[source_to_source];
Console.WriteLine(third_value);
}
int[,] ratios = new int[3, 9] { { 66, 97, 127, 94, 140, 180, 140, 208, 269 }, { 76, 109, 140, 102, 127, 188, 132, 165, 244 }, { 86, 97, 152, 109, 155, 193, 142, 201, 251 } };
Console.WriteLine(ratios[valueDict_source_to_source[source_to_source], array[valueDict[ground], valueDict[moment_magnitude]]]);
ratio_peak = (ratios[valueDict_source_to_source[source_to_source], array[valueDict[ground], valueDict[moment_magnitude]]]);
Console.WriteLine(ratio_peak);
Console.ReadKey();
}
}
}
【问题讨论】:
-
你的字典有一个键
rock但你的ground变量是Rock。它们必须相同。 -
你能不改用
double moment_magnitude = 6.5然后设置valueDict = new Dictionary<double, int> ...吗? -
@ataraxia 在 OP 的代码中,字典的键还包含
"rock"- 这将如何与Dictionary<double, int>一起使用?虽然我确实认为将双精度数表示为字符串并不是一个好主意 - 可能有两个单独的字典是最好的方法。 -
@MattJones 我的错,我错过了。取决于 OP 的应用程序如何处理字符串并加倍。
-
@dazedandconfused 你想修复你的异常吗?还是更好的方法?
标签: c# arrays dictionary