user2534915
user2534915

Reputation: 15

How to avoid run time error while working with dictionary

I have a piece of code that represent Dictionary and search key array.

Dictionary<string, string> items = new Dictionary<string, string>()
                                   {
                                     {"1","Blue"},
                                     {"2","Green"},
                                     {"3","White"}
                                    };

string[] keys = new[] { "1", "2", "3", "4" };

How to safely avoid the run time error when i pass a key that is not present in dictionary?

Upvotes: 1

Views: 211

Answers (2)

user2488066
user2488066

Reputation:

Use either ContainsKey or TryGetValue to check the existence of a key.

string val = string.Empty;
 foreach (var ky in keys)
 {

                if (items.TryGetValue(ky, out val))
                {
                    Console.WriteLine(val);
                }

     }

or

foreach (var ky in keys)
 {

   if (items.ContainsKey(ky))
    {
      Console.WriteLine(items[ky]);
    }
  }

Though TryGetValue is faster than ContainsKey use it when you want to pull the value from dictionary.if you want to check the existence of key use ContainsKey.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500425

How to safely avoid the run time error when i pass a key that is not present in dictionary?

You haven't shown how you're currently trying to do it, but you can use Dictionary<,>.TryGetValue:

foreach (string candidate in keys)
{
    string value;
    if (items.TryGetValue(candidate, out value))
    {
        Console.WriteLine("Key {0} had value {1}", candidate, value);
    }
    else
    {
        Console.WriteLine("No value for key {0}", candidate);
    }
}

Upvotes: 2

Related Questions