Wednesday, 22 June 2016

Use reflection to convert the dictionary object into our classes.

Use reflection to convert the dictionary object into our classes.

Following GetObject method converts dictionary object into any class type(T).
 public static T GetObject<T>(Dictionary<string, object> dict)
        {
            Type type = typeof(T);
            var obj = Activator.CreateInstance(type);

            if (dict == null)
            {
                return default(T);
            }

            foreach (var kv in dict)
            {
                if (kv.Value != DBNull.Value)
                {
                    if (type.GetProperty(kv.Key) != null)
                    {
                        type.GetProperty(kv.Key).SetValue(obj, kv.Value);
                    }
                }
            }

            return (T)obj;
        }

Usage:
 Dictionary<string, object> retreivedData = new  Dictionary<string, object>();
retreivedData["Id"]=1;
retreivedData["Name"]="My Name";

var data = GetObject<Customer>(retreivedData);


Following GetCollectionObject method converts dictionary object into any class type collection(T).
        public static List<T> GetCollectionObject<T>(Dictionary<int, Dictionary<string, object>> dict)
        {
            Type type = typeof(T);
            IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
            if (dict == null)
            {
                return (List<T>)list;
            }

            foreach (var kv in dict)
            {
                object obj = Activator.CreateInstance(type);
                foreach (var objValue in kv.Value)
                {
                    if (objValue.Value != DBNull.Value)
                    {
                        if (type.GetProperty(objValue.Key) != null)
                        {
                            type.GetProperty(objValue.Key).SetValue(obj, objValue.Value);
                        }
                    }
                }
                list.Add(obj);
            }

            return (List<T>)list;
        }

No comments:

Post a Comment