Amazon.com Widgets August 2011

WilliaBlog.Net

I dream in code

About the author

Robert Williams is an internet application developer for the Salem Web Network.
E-mail me Send mail
Code Project Associate Logo
Go Daddy Deal of the Week: 30% off your order at GoDaddy.com! Offer expires 11/6/12

Recent comments

Archive

Authors

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.


Generic AddOrUpdate Extension for IDictionary (C#)

I recently came across a situation where the properties of a class were adding the value to an internal dictionary of key value pairs which made it easy to loop through and return a JSON string. This worked great until we later ran into a situation where we needed to update a property after it had already been set, which of course generated a "System.ArgumentException: An item with the same key has already been added". While it is easy enough to add a check to see if the dictionary already contains the key you are attempting to add, doing this for every property would be way too much code repetition so an Extension Method seemed appropriate.

Edit: However, it has since been pointed out in the comments area below (thanks jeanie77!), that I could just as easily have used the indexer, e.g. dictionary[key] = value to achieve the same results. If that index does not already exist it will be created, and if it does it will be updated. I prefer this solution to the extension method because it is more readable, native to the framework and can be reused in other solutions without having to find and copy the Extension code also.

If you still want to use the extension method, add the following code to a static class in your solution, then add that namespace to the list of namespaces you are "using" at the top of any class that might need it, and your Dictionary will have a .AddOrUpdate(key, value) method:

 

        public static IDictionary<TKey,TValue> AddOrUpdate<TKey,TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
        {
            if(dictionary.ContainsKey(key))
            {
                dictionary[key] = value;
            }
            else
            {
                dictionary.Add(key, value);
            }

            return dictionary;
        }

 


Categories: C#
Posted by Williarob on Tuesday, August 30, 2011 8:54 AM
Permalink | Comments (0) | Post RSSRSS comment feed