Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store key/value pair in C#(4.0)?

Tags:

c#

c#-4.0

I would like to know how to Store Key/Value Pair in C# 4.0?

For example, in Java HashTable or HashMap used to store key/value pairs.. But How i do it in C#?

like image 359
Saravanan Avatar asked Apr 27 '11 09:04

Saravanan


2 Answers

You can use the Hashtable class, or a Dictionary<TKey, TValue> if you know the specific types that you're storing.

Example:

// 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);
}
like image 113
Rudi Visser Avatar answered Oct 03 '22 10:10

Rudi Visser


You can check the Dictionary data structure, using string for the key type and whatever you data's type is for the value type (possibly object if multiple types of data items).

like image 23
npinti Avatar answered Oct 03 '22 10:10

npinti