如何在C#(4.0)中存储键值对?

7

我想知道如何在C# 4.0中存储键/值对?

例如,在Java中,使用HashTableHashMap来存储键/值对,但是在C#中该如何实现呢?

4个回答

26
你可以使用 Hashtable 类,或者如果你知道具体存储的类型,可以使用 Dictionary<TKey, TValue>

示例:

// Loose-Type
Hashtable hashTable = new Hashtable();
hashTable.Add("key", "value");
hashTable.Add("int value", 2);
// ...
foreach (DictionaryEntry dictionaryEntry in hashTable) {
    Console.WriteLine("{0} -> {1}", dictionaryEntry.Key, dictionaryEntry.Value);
}

// Strong-Type
Dictionary<string, int> intMap = new Dictionary<string, int>();
intMap.Add("One", 1);
intMap.Add("Two", 2);
// ..
foreach (KeyValuePair<string, int> keyValue in intMap) {
    Console.WriteLine("{0} -> {1}", keyValue.Key, keyValue.Value);
}

非常感谢您。但是如何获取特定值呢?例如,我想在这里获取两个值... - Saravanan
1
你可以像使用普通的数组访问器一样使用 intMap["Two"]。由于强类型化,你将获得一个 int 类型的对象,而使用 Hashtable 时只会获得一个 object 类型的对象。 - Rudi Visser
你可以通过以下方式获取一个值:intvalue = hashTable["Two"] - Kevin

2
你可以使用 string 作为键类型,使用你的数据类型作为值类型(如果数据项有多种类型,则可能使用 object),来检查 字典 数据结构。

1

1

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