Reputation: 11612
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#?
Upvotes: 8
Views: 48742
Reputation: 22019
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);
}
Upvotes: 26
Reputation: 52195
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).
Upvotes: 2
Reputation: 13574
Saravanan
Java Map equals C# Dictionary (more or less)... and you'll want the generics version, of course.
This (at a quick glance) looks like a decent example. http://www.dotnetperls.com/dictionary-lookup
Also you might want to take a geezer at: http://www.25hoursaday.com/CsharpVsJava.html ... I've found it to be extremely helpful with getting up-to-speed in C#.
Cheers. Keith.
Upvotes: 1
Reputation: 570
You can use Dictionary in c# see examples at http://www.dotnetperls.com/dictionary-keys
Upvotes: 1