Monday, January 28, 2013

Convert an object’s property values to a dictionary of string,object

Here is a simple helper function that converts any class object to a dictionary of string,object, where the key is the PropertyName:

public static class ReflectionHelper
{
    public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
   {
       BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
       Dictionary<string, object> dictionary = new Dictionary<string, object>();

       foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
       {
           if (property.CanRead)
               dictionary.Add(property.Name, property.GetValue(model, null));
       }

       return dictionary;
   }
}

public class Test
{
    public string Name{get;set;}
}

void Main()
{
    Test t = new Test{Name = "Raj Rao"};
    foreach(var v in t.ToDictionary())
    {
           Console.WriteLine(v.Key + ":" + v.Value);
    }

}

The output will be:

Name: Raj Rao

This again was inspired by some of the Helper functions available in Asp.Net’s MVC HTML helper class.

No comments: