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#?
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);
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With