从哈希表中获取特定键

Getting a specific key from within a hashtable

所以我有这个哈希表

Hashtable Months = new Hashtable();
Months.Add(0, "JANUARY");
Months.Add(1, "FEBRUARY");
Months.Add(2, "MARCH");
Months.Add(3, "APRIL");
Months.Add(4, "MAY");
Months.Add(5, "JUNE");
Months.Add(6, "JULY");
Months.Add(7, "AUGUST");
Months.Add(8, "SEPTEMBER");
Months.Add(9, "OCTOBER");
Months.Add(10, "NOVEMBER");
Months.Add(11, "DECEMBER");

我希望用户输入月份,例如"May" 能够从我的程序中的数组中检索索引[4]。

string Month = Console.ReadLine();

基本上是根据输入的相应月份的数字检索索引。

从您的 Hashtable 中以 DictionaryEntry 格式获取元素

foreach (DictionaryEntry e in Months)
{
    if ((string)e.Value == "MAY")
    {
        //get the "index" with e.Key
    }
}

试试这个

var key = Months.Keys.Cast<int>().FirstOrDefault(v => Months[v] == "MAY");

注意:不要忘记包含此命名空间 - using System.Linq;

您可以只使用循环执行它;

    public List<string> FindKeys(string value, Hashtable hashTable)
    {
        var keyList = new List<string>();
        IDictionaryEnumerator e = hashTable.GetEnumerator();
        while (e.MoveNext())
        {
            if (e.Value.ToString().Equals(value))
            {
                keyList.Add(e.Key.ToString());
            }
        }
        return keyList;
    }

用法;

var items = FindKeys("MAY",Months);

如果要从月份名称中查找索引,Dictionary<string, int> 会更合适。我交换参数的原因是,如果您只想查找索引,而不是反过来,这样会快得多。

您应该将字典声明为不区分大小写,以便它检测例如 mayMaymAyMAY 是同一事物:

Dictionary<string, int> Months = new Dictionary<string, int>(StringComparison.OrdinalIgnoreCase);

然后只要你想得到月份索引就使用它的TryGetValue() method:

int MonthIndex = 0;
if(Months.TryGetValue(Month, out MonthIndex)) {
    //Month was correct, continue your code...
else {
    Console.WriteLine("Invalid month!");
}