views:

557

answers:

7

I want to create a class which will have two properties, e.g. key & value.

And I want one method which will give me a value based on the key.

So what is the code? I know Hashtable but how to implement it in C#? Can I have a string as a key?

+4  A: 

Look at the Dictionary<TKey, TValue> class: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Daniel Earwicker
+1  A: 

Use Dictionary<string, TypeOfYourVAlue>

Grzenio
+2  A: 

A Dictionary<string, T> will do all you want.

Mehrdad Afshari
thank you, Mehrdad!
Vikas
+4  A: 

Here is the best way implement this (I use Int32 as an example of a type to store):

Dictionary<String,Int32> dictionary = new Dictionary<String,Int32>
{
    // this just loads up the list with
    // some dummy data - notice that the
    // key is a string and the value is an int
    { "one", 1 },
    { "two", 2 },
    { "three", 3 },
};

Now you can grab values from the Dictionary<,> like this:

dictionary["one"]; // returns 1
dictionary["two"]; // returns 2
Andrew Hare
+1  A: 

Dictionary(TKey, TValue) Class

PoweRoy
+1  A: 

There are a couple more implementations as well. There's the HashSet which is designed for set operations and the KeyedCollection which is an easily serializable hash table.

Will
+1  A: 

... and also System.Collections.Specialized.NameValueCollection, which is roughly equivalent to Dictionary<string,string>, but allows storing multiple string values under the same key value. To quote MSDN documentation:

This class can be used for headers, query strings and form data.

Igor Brejc