Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. public static class ReflectionHelper
  2. {
  3.     public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
  4.    {
  5.        BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
  6.        Dictionary<string, object> dictionary = new Dictionary<string, object>();
  7.  
  8.        foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
  9.        {
  10.            if (property.CanRead)
  11.                dictionary.Add(property.Name, property.GetValue(model, null));
  12.        }
  13.  
  14.        return dictionary;
  15.    }
  16. }
  17.  
  18. public class Test
  19. {
  20.     public string Name{get;set;}
  21. }
  22.  
  23. void Main()
  24. {
  25.     Test t = new Test{Name = "Raj Rao"};
  26.     foreach(var v in t.ToDictionary())
  27.     {
  28.            Console.WriteLine(v.Key + ":" + v.Value);
  29.     }
  30.    
  31.     var k = new {J="J1",K="K1",L="Lm"};
  32.     foreach(var v in k.ToDictionary())
  33.     {
  34.         Console.WriteLine(v.Key + ":" + v.Value);
  35.     }
  36. }