如您所见,我有一个由 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/