c# - 在 C# 中使用字符串调用哈希表

标签 c# hashtable

如您所见,我有一个由 GetEdinburgh() 调用的哈希表 但是这个程序需要运行可变的时间,并且每次都需要调用不同的哈希表。如何用 GetTown() 之类的字符串替换 GetEdinburgh()

static Hashtable GetEdinburgh()
{
    Hashtable hashtable = new Hashtable();
    hashtable.Add("Aberdeen", 129);
    hashtable.Add("Ayr", 79);
    hashtable.Add("Fort_William", 131);
    hashtable.Add("Glasgow", 43);
    hashtable.Add("Inverness", 154);
    hashtable.Add("St_Andrews", 50);
    hashtable.Add("Stirling", 36);
    return hashtable;
}


static void Main(string[] args)
{
    int total = 1000;
    string Town = "";

    Hashtable hashtable = GetEdinburgh(); //how can I change this to a string?
    foreach (DictionaryEntry entry in hashtable)
    {
        if (Convert.ToInt32(entry.Value) < total)
        {
            total = Convert.ToInt32(entry.Value);
            Town = entry.Key.ToString();
        }

    }
    Console.WriteLine(Town + ", " + total + "km");
    Console.ReadLine();
}

我可能没有具体说明我的问题。上面的当前代码工作正常,但我需要扩展它。我需要调用比上面提供的哈希表更多的哈希表,但我不能直接调用它。我需要有一个字符串值,该值在每次实现循环以调用新表时都会更改。但我无法将 system.Collections.hashtable 转换为字符串。

最佳答案

更好的方法是这样写:

static Hashtable GetHashtable(string Table )
    {
        Hashtable hashtable = new Hashtable();
           switch(table)
          {
        case "Edinburgh":
        hashtable.Add("Aberdeen", 129);
        hashtable.Add("Ayr", 79);
        hashtable.Add("Fort_William", 131);
        hashtable.Add("Glasgow", 43);
        hashtable.Add("Inverness", 154);
        hashtable.Add("St_Andrews", 50);
        hashtable.Add("Stirling", 36);
        break;
           ................
        return hashtable;
    }

您可以将字符串传递给方法并获取值。

Click answered if the answer really answers your question..

关于c# - 在 C# 中使用字符串调用哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12930281/

相关文章:

java - 在 ConcurrentSkipListMap Java 中插入空值

java - Java 哈希表

c# - 在 C# 中的哈希表中向单个键添加多个值?

powershell - 带点的哈希表键

c# - 为什么枚举中的位置标记(如第一个或最后一个)被认为是不好的做法?

c# - 根据按月过滤的两个日期值获取数据

c - 结构体键的简单查找

c# - 从 Azure 表存储检索超过 100 万条记录

c# - 如何从图像控制 Windows 8 应用程序将图像保存到文件夹

c# - 代码契约问题