从哈希表中获取特定的键

5

我有一个 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");

我希望用户输入一个月份,比如“五月”,然后能够从我的程序中的一个数组中检索到index[4]。

string Month = Console.ReadLine();

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

4
为什么不在这里使用 Dictionary<int,string>(),它有一个名为TryGetValue()的方法? - FrankM
4个回答

4

试试这个

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

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

我不太明白这个,但似乎它起作用了,我非常感激一个详细解释。谢谢。 - K.John
对于哈希表中的每个键,检查其值并返回与该月份匹配的第一个值(如果未找到,则返回null)。 - A Friend
@K.John:在哈希表中访问值的语法是 - YourHashTable[key]。在你的HashTable中,key 的类型是 int,而 value 的类型是 string。因此要获取 key(即 int 类型),我们需要将它先转换为 int,并使用 linq 的 FirstOrDefault 方法,该方法会在每个键中进行内部迭代,查找匹配的值并返回其相关的键。 - Krishnraj Rana

0

DictionaryEntry格式从你的Hashtable中获取元素

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

0

你可以使用循环来执行它;

    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);

谢谢,我会尝试你的方法。 - K.John

0

如果您想按月份名称查找索引,Dictionary<string, int> 将更适合。我交换参数的原因是,如果您只想查找索引,而不需要反向查找,这将更快。

您应将字典声明为不区分大小写,以便它将 mayMaymAyMAY 视为相同的内容:

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

然后,每当您想要获取月份索引时,只需使用它的 TryGetValue() 方法

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接