Converting anonymous object to Dictionnary<string, string><!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Converting anonymous object to Dictionnary<string, string>

Posted on: June 12, 2014

Some Asp.Net MVC Html Helpers use the possibility to add anonymous object as parameter to assign key value. It is the case of HtmlAttributes parameter. If you want to create your own Html Helper or simply having the possibility to use anonymous object, you may stumble into the case that you need to enumerate keys and values.

1public string Url(string action, string controller, string area = null, object routeValues = null) {
2 //Code here

The code above is an example. You may want to have a method that generate an url from some parameters. The last parameter named "routeValues" is of type object. This one is created to be used for anonymous object.

1Url("action", "controller", "area", new {Id = "123", Name="This is my name"});

The Url method can then loop through all the properties. Something that can help you is to create an anonymous method for object that convert everything into an IDictionary where it will be easy to manipulate keys (property name) and values.

1public static class ObjectExtensions {
2 public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) { return source.GetType().GetProperties(bindingAttr).ToDictionary ( propInfo => propInfo.Name, propInfo => propInfo.GetValue(source, null) ); } }

It uses reflection to get all properties and from these properties to get all values.

Here is a unit test for the AsDictionary extension method.

2public class ObjectExtensionsTest {
3 [TestMethod]
4 public void GivenAnObject_WhenThisOneHasMultipleProperties_ThenDictionary()
5 {
6 // Arrange
7 var objectToConvert = new {Id="Test", Name="Test2"};
9 // Act
10 var dictionary = objectToConvert.AsDictionary();
12 // Assert
13 Assert.AreEqual(2,dictionary.Keys.Count);
14 Assert.AreEqual(objectToConvert.Id,dictionary["Id"]);
15 Assert.AreEqual(objectToConvert.Name,dictionary["Name"]);
16 }