Serializing a Dictionary

For better or for worse, dictionaries are not allowed in .net Web API’s.  List’s are allowed, and what’s a dictionary, if not a list of key, value pairs?  So, I wrote this extension method to “serialize” a dictionary.

public static class ExtensionMethods
{
     public static List<KeyValuePair<T1, T2>> Serialize<T1, T2> (this Dictionary<T1, T2>)
     {
          List<KeyValuePair<T1, T2>> list = new List<KeyValuePair<T1, T2>>();
          list.AddRange(dictionary);
          return list;
     }
}

Then, you call it like this:

Dictionary<int, string> wordsThatStartWithB = new Dictionary<int, string>()
{
     { 1, "Bob" },
     { 2, "Blue" },
     { 3, "Bone" },
     { 4, "Bow" }
};

return wordsThatStartWithB.Serialize();

Of course, there are probably better ways of doing this, which is why I will be open sourcing my extensions library in the coming weeks, and will have a blog post about each one. Do you have any recommendations on improving this?

Advertisements