今天跟taoli同学说了下,我要存储一组名称-键值的数据表,怎么弄,他就一句话,你个fc。我平生最讨厌三种人 不识数的人,种族歧视的人,黑人。
用哈希表啊。
我早就把哈希表忘记到九霄云外去了。今天恶补了一下下,C#有很方便的实现,System.Collections.hashtable
还有支持泛型的dictionary 用以提高效率。很方便。
下面是一个简单的使用System.Collections.Hashtable对象的示例:
public static void UseNonGenericHashtable()
{
// 创建并相似一个Hashtable.
Hashtable numbers = new Hashtable();
numbers.Add(1, "one"); // 发生装箱操作
numbers.Add(2, "two"); // 发生装箱操作
// 显示Hashtable中所有的键值对
// 在每一个递归中都会发生一次拆箱操作
foreach (DictionaryEntry de in numbers)
{
Console.WriteLine("Key: " + de.Key + "\tValue: " + de.Value);
}
numbers.Clear();
}
下面是一个使用System.Collections.Generic.Dictionary<T,U>对象的相似的代码:
public static void UseGenericDictionary()
{
// 创建并显示一个Dictionary.
Dictionary<int, string> numbers = new Dictionary<int, string>();
numbers.Add(1, "one");
numbers.Add(2, "two");
// 显示所有Dictionary中的键值对
foreach (KeyValuePair<int, string> kvp in numbers)
{
Console.WriteLine("Key: " + kvp.Key + "\tValue: " + kvp.Value);
}
numbers.Clear();
}

浙公网安备 33010602011771号