One of the nice things about object oriented programming is the ability to add capabilities to objects to suit your needs.  I've extended my own classes before, but one thing I had not done was create an extension for a standard class.

Today I found myself wishing that the Dictionary class had a Prepend method so I could add something to the front of the list easily.  Like most developers, I did some looking on the internet to see if anyone else had created something like what I was wanting, plus looking for just general examples.  I found nothing of the former, but plenty of the latter.  One really nice example was found here (http://gltaurus.blogspot.com/2010/07/dictionary-class-extensions-copyto-sort.html) from a couple of years ago.  Using that as a nice guideline, I created this:

namespace MiscClasses
{
    public static class DictionaryExtensions
    {
        public static void Prepend<T, V>(this Dictionary<T, V> source, 
T newKey, V newValue)
        {
            // load existing dictionary into temporary list
            List<KeyValuePair<T, V>> entries = new List<KeyValuePair<T, V>>(source);
            // clear source
            source.Clear();
            // add the new item to source
            source.Add(newKey, newValue);
            // now add the original values back into the dictionary
            foreach (var item in entries)
            {
                source.Add(item.Key, item.Value);
            }
        }
    }
}

It's a very simple solution, but it makes the class very usable for what I needed: adding a default selection for dropdowns.  My repository methods return a Dictionary with available key/values.  Anyways, I know this is nothing new to those of you more experienced than I, but it was nice to do.

Category: coding mvc
0