tags:

views:

51

answers:

3

I have a dictionary pair i make an object of dictionary "paramList", now i have added key and value pair to that object, now i want to know if on the some other page i pass the object paramList in some method and on that page i know the key and i want to access it's corresponding value then how can i do that I have object like this

 Dictionary<string, object> paramList = new Dictionary<string, object>();
 paramList.Add("@courseId", course_id);
 paramList.Add("@passoutYear", passoutYear);
 paramList.Add("@currentBacklog", currentBacklog);
 paramList.Add("@sex", sex);

now if i know the key @key and want to know it's corresponding value i also have the object

+4  A: 

If I understand your question correctly, you want to know if the key exists in the dictionary and then retrieve the value.

Perhaps the simplest way is using TryGetValue

string key = "@key";
object value = null;
if (paramList.TryGetValue(key, out value))
{
    // the key exists and the related value is now in value
}
else
{
    // the key does not exist
}
Tim Carter
give a glance at this sir ...please i m dire need to rid myself of from this issue i am stuck on how to sort circuit empty parameter value from the query ...http://stackoverflow.com/questions/3509538/asp-net-sql-or-collection-problem
NoviceToDotNet
+2  A: 
//First check if the key exists in the dictionary and then get the item.
if(paramList.ContainsKey("some-key"))
{
 object value = paramList["some-key"];
}

Edit Or maybe with an extension method. (To not do a double lookup).

static class DictionaryExtensions
{
    public static TValue GetValueOrDefault<TKey,TValue>(this IDictionary<TKey,TValue> dict, TKey key)
    {
        TValue value;
        if(dict.TryGetValue(key, out value))
            return value;
        return default(TValue);
    }
}

//Example usage
paramList.GetValueOrDefault("mykey") ?? "mykey didn't exist";
Jesper Palm
This performs double dictionary lookup
abatishchev
Probably, even shorter `return dict.TryGetValue(key, out value) ? value : default(TValue);`
abatishchev
And another suggestion - often such methods has an optional param (via overload or another way) representing default value for lookup failure case, i.e. `return dict.TryGetValue(key, out value) ? value : defaultValue ?? default(TValue);`
abatishchev
A: 

Just for your information, you can also initialize your dictionary using next approach:

Dictionary<string, object> paramList = new Dictionary<string, object>
{
    { "@courseId", course_id },
    { "@passoutYear", passoutYear },
    { "@currentBacklog", currentBacklog },
    { "@sex", sex },
};

It's called "collection initializer"

abatishchev