从哈希表中获取特定密钥

时间:2017-12-15 15:53:38

标签: c# collections hashtable

所以我有这个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();

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

4 个答案:

答案 0 :(得分:3)

试试这个

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

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

答案 1 :(得分:0)

Hashtable格式

获取DictionaryEntry中的元素
foreach (DictionaryEntry e in Months)
{
    if ((string)e.Value == "MAY")
    {
        //get the "index" with e.Key
    }
}

答案 2 :(得分:0)

您可以使用循环执行它;

- name: Send GET request to target
  shell: wget -O - http://some.download.page | grep '>Latest version<' | sed -n 's/.*href="\(.*\)".*/\1/p'
  register: web
  args:
      warn: False

- name: Show download link
  debug:
    msg: "{{ web.stdout }}"

<强>用法;

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

答案 3 :(得分:0)

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