【问题标题】:How to access values from a table using dictionary and array functions in C#如何在 C# 中使用字典和数组函数访问表中的值
【发布时间】: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&lt;double, int&gt; ...吗?
  • @ataraxia 在 OP 的代码中,字典的键还包含 "rock" - 这将如何与 Dictionary&lt;double, int&gt; 一起使用?虽然我确实认为将双精度数表示为字符串并不是一个好主意 - 可能有两个单独的字典是最好的方法。
  • @MattJones 我的错,我错过了。取决于 OP 的应用程序如何处理字符串并加倍。
  • @dazedandconfused 你想修复你的异常吗?还是更好的方法?

标签: c# arrays dictionary


【解决方案1】:

这是一个使用更面向对象的方法的想法。

首先,您创建一个代表每条记录的类,例如:

public class Surface
{
    /// <summary>
    /// Name of the surface e.g. RockA
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Moment magnitude Mw
    /// </summary>
    public double Moment { get; set; }

    /// <summary>
    /// Source to site distance from 0 to 20 km
    /// </summary>
    public int SourceToSite20 { get; set; }

    /// <summary>
    /// Source to site distance from 20 to 50 km
    /// </summary>
    public int SourceToSite50 { get; set; }

    /// <summary>
    /// Source to site distance from 50 to 100 km
    /// </summary>
    public int SourceToSite100 { get; set; }
}

然后创建它们的列表,确保每个组的表面名称相同,例如 RockA:

List<Surface> surfaces = new List<Surface>();
surfaces.Add(new Surface
{
    Name = "RockA",
    Moment = 6.5,
    SourceToSite20 = 18,
    SourceToSite50 = 23,
    SourceToSite100 = 30
});

surfaces.Add(new Surface
{
    Name = "RockA",
    Moment = 7.5,
    SourceToSite20 = 43,
    SourceToSite50 = 56,
    SourceToSite100 = 68
});

surfaces.Add(new Surface
{
    Name = "Stiff soil",
    Moment = 6.5,
    SourceToSite20 = 35,
    SourceToSite50 = 41,
    SourceToSite100 = 48
});

[...]

现在您可以更轻松地访问数据,例如,使用 Linq 查询:

获取表面为“RockA”的所有记录:

List<Surface> rocks = surfaces.Where(x => x.Name == "RockA").ToList();

矩 = 6.5 的曲面:

List<Surface> magintude65 = surfaces.Where(x => x.Moment == 6.5).ToList();

来源到 25 到 55 之间的距离

List<Surface> result = surfaces.Where(x => x.SourceToSite50 >= 25 && x.SourceToSite100 <= 55).ToList();

如果不想创建类,也可以使用元组列表:

var surfaces = new List<Tuple<string, double, int, int, int>>();
surfaces.Add(new Tuple<string, double, int, int, int>("RockA", 6.5, 18, 23, 30));
[...]

然后您可以进行相同类型的查询,但我建议您使用一个类,无论如何,这就是它们的用途。

【讨论】:

    【解决方案2】:

    默认情况下,带有字符串键的字典使用默认的字符串比较器,它区分大小写。如果您将 ground 变量值更改为“rock”而不是“Rock”,您的代码将起作用。

    【讨论】:

    • 此外,OP 在制作字典时也可以使用 StringComparer.InvariantCultureIgnoreCase。那么大小写无关紧要。
    猜你喜欢
    • 2020-06-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多