Tuesday, December 18, 2012

Convert Dictionary into Strongly Typed Class


There are few things you have to consider before conversion of dictionary into strongly typed class object.

1 - To detect in which class you want to convert into dictionary. For this purpose you need generic (Template) where you will specify in which class you want to convert.

2 - Get the properties of the strongly typed class using reflection.

3 - Create the object of the Generic . and get the reference of it.

4 - Iterate the properties of object and search the dictionary contains that field or column, if its find and writeable then set the value using reflection but cast the values into the strongly typed of a column too.

Here's the demo.

   class Emp {
      public string Name { get; set; }
      public string TechnologyExpert { get; set; }
      public int Salary { get; set; }
      public override string ToString(){
         return Name + "-----" + TechnologyExpert + "-----" + Salary;
      }
   }
   class Cust{
      public string Name { get; set; }
      public string Company { get; set; }
      public override string ToString(){
         return Name + "------" + Company;
      }
   }

/// Please use angle bracket here too.
   class ConvertIntoStronglyTyped  where T: new() {
      public static T ConvertMe(Dictionary objectDict)
      {
         var properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
       
         Object obj = new T();
       
         foreach (var property in properties)
            if (property.CanWrite && objectDict.ContainsKey(property.Name))            
               property.SetValue(obj, Cast(property.PropertyType.FullName, objectDict[property.Name]), null);                  

         return (T)obj;
      }

      private static object Cast(string propertyTypeName, object value) {
         string strFullName = typeof(string).FullName;
         string intFullName = typeof(int).FullName;
         string floatFullName = typeof(float).FullName;

         if (strFullName == propertyTypeName)   return value.ToString();
         if (intFullName == propertyTypeName)   return int.Parse(value.ToString());
         if (floatFullName == propertyTypeName) return int.Parse(value.ToString());
       
         return value;
      }
   }

Execute the code.

class Program
   {
      static void Main(string[] args)
      {
         Dictionary consolidatedValues = new Dictionary();
       
         consolidatedValues.Add("Name", "Sohail");
         consolidatedValues.Add("TechnologyExpert", "C#");
         consolidatedValues.Add("Salary", "200");
         consolidatedValues.Add("Company", "ABC .Com");

// I noticed the less than greater than bracket is not visible, use simple the angle brackets.
         Emp emp = ConvertIntoStronglyTyped&ltEmp&gt.ConvertMe(consolidatedValues);

         Cust cust = ConvertIntoStronglyTyped.ConvertMe(consolidatedValues);
         Console.WriteLine(emp);
         Console.WriteLine(cust);
      }
   }

Please let me know incase you are facing issue and have more questions regarding the reflections or generics.




2 comments:

  1. SetValue it too slow, why don't use Reflection.Emit?

    ReplyDelete
  2. chung cư 89 phùng hưng
    tiếng anh giao tiếp cho trẻ em

    chung cư newskyline văn quán "Thiếu gia, quân đội của địch đông như vậy, người chỉ phái một vài chi
    bộ đội liệu có quá ít không? Dù sao Thiên Long quốc cũng là cơ sở của
    chúng ta, bọn họ xâm lược Thiên Long, thì chúng ta cũng giúp đỡ Thiên
    Long quân đội đi xâm chiếm lại Lôi Ngạo và Tạp Tu Tư. Chúng ta cầm giữ
    Lôi Ngạo từ phía Nam và Tạp Tu Tư từ phía Đông đi tới. Làm cho lãnh thổ
    của Thiên Long đế quốc gia tăng một phần nhỏ là có khả năng mà!" Hi La
    cười nói. Mười đầu Cự long? Chuyện nhỏ như chim con thỏ, ta chỉ cần xuất
    ra một liên đội là bắt được ngay! Còn số quân đội kia ư? Hơn một vạn thủ
    hạ Kiếm thánh của lão tử lại không đánh cho bọn ngươi tan như đám cát ấy ư?

    "Không! Ta chỉ định phái hai toán bộ đội đi ra ngoài là được! Nanh Sói
    toàn sư, các ngươi dùng Phi long di chuyển đến Lạc Nhật Hạp Cốc, nhiệm
    vụ của các ngươi là đem mười đầu Cự long đáng chết kia về đây luyện
    dược! Còn nữa, cũng là xem xét cơ hội mà hành động phản công Lôi Ngao và
    Tạp Tu Tư, như vậy cứ theo ngươi nói đi, bắt buộc bọn họ ký hiệp ước
    nhường một phần lãnh thổ cho chúng ta!"

    "Vâng! Nanh Sói lĩnh mệnh!" Hi La vẻ mặt hưng phấn trả lời, rốt cục cũng
    được xuất chiến, thật không dễ dàng a!


    hateco hoàng mai
    chung cư hà nội

    dịch vụ hoàn thuế
    dịch vụ kế toán thuế
    dịch vụ quyết toán thuế
    khoá học kế toán thuế
    trung tâm kế toán
    dịch vụ báo cáo thuế hàng tháng

    dich vu ke toan noi bo

    ReplyDelete