C# 从哈希表中获取特定键
所以我有这个哈希表C# 从哈希表中获取特定键,c#,collections,hashtable,C#,Collections,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
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();
基本上是从输入的相应月份的编号中检索索引。以
字典entry
格式从哈希表中获取元素
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");
var key=Months.Keys.Cast().FirstOrDefault(v=>Months[v]==“MAY”);
注意:不要忘记使用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;
}
如果您想从月份名称中查找索引,则a更合适。我交换参数的原因是,如果您只想查找索引,而不想反过来查找,那么这将快得多
您应该将字典声明为不区分大小写,以便它检测到例如may
、may
、may
和may
等相同的内容:
Dictionary<string, int> Months = new Dictionary<string, int>(StringComparison.OrdinalIgnoreCase);
为什么不使用Dictionary()
有一种TryGetValue()
方法我不太明白这一点,但它似乎起了作用,我真的很感谢您的详细介绍或解释。谢谢您,对于哈希表中的每个键,请检查其值并返回与月份匹配的第一个键(如果未找到,则返回null)@K.John:在哈希表中,访问值的语法是-YourHashTable[key]
。在哈希表中,键的类型为int
,值的类型为string
。因此,要获得int
类型的键,我们需要首先将其转换为int,并使用linq的FirstOrDefault方法,该方法在内部迭代每个键,找到匹配值并返回其相关键。谢谢,我将尝试您的方法。
Dictionary<string, int> Months = new Dictionary<string, int>(StringComparison.OrdinalIgnoreCase);
int MonthIndex = 0;
if(Months.TryGetValue(Month, out MonthIndex)) {
//Month was correct, continue your code...
else {
Console.WriteLine("Invalid month!");
}