【问题标题】:Getting a specific key from within a hashtable从哈希表中获取特定键
【发布时间】:2018-05-29 20:49:38
【问题描述】:

所以我有这个哈希表

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

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

【问题讨论】:

  • 为什么不使用Dictionary<int,string>() 还有TryGetValue() 方法

标签: c# collections hashtable


【解决方案1】:

如果您想从月份名称中查找索引,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!");
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,我试试你的方法。
    【解决方案3】:

    试试这个

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

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

    【讨论】:

    • 不太明白这一点,但它似乎有效,我真的很感激故障或解释。不过还是谢谢
    • 对于哈希表中的每个键,检查它的值并返回与月份匹配的第一个(如果没有找到则返回 null)
    • @K.John:在哈希表中访问值的语法是-YourHashTable[key]。在您的 HashTable 中,键的类型为 int,值的类型为 string。因此,要获取int 类型的键,我们需要首先将其转换为 int 并使用 linq 的 FirstOrDefault 方法,该方法在内部迭代每个键并找到匹配的值并返回其相关键。
    【解决方案4】:

    Hashtable 中以DictionaryEntry 格式获取元素

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

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 1970-01-01
      • 2012-07-06
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      相关资源
      最近更新 更多