Wednesday, October 19, 2016

Converting Object Specific Properties to IDictionary<string, Object> Using Lambda Expression

Below function will convert the specific properties of any class to IDictionary<string, object>

The function is  an extension method for object type and takes params array of Expression<Func<T, object>>. The reason for outputting object in Func is to output any primary type such int, long, string, float and etc.

Registration Example Class



public class Registration 
{
        public int RegId {get; set;}
        public string RegName {get; set;}
        public string RegNotRequired {get; set;}
        public DateTime RegDate {get; set;}
        public string RegLocation {get; set;}
}


Example



Registration reg = new Registration 
                            {RegId = 1,
                             RegName = "Murtaza", 
                             RegNotRequired="Not Important", 
                             RegDate="2012-09-19", 
                             RegLocation ="Pakistan"};
IDictionary<string, object> val = reg.AsKeyAndValue(
                                      r => r.RegId, r => r.RegName, 
                                      r => r.RegDate, r => r.RegLocation);




Extension Method


Following function converts the class properties into IDictionary<string, object>


  public static IDictionary<string,object> AsObjectValueDictionary(this T obj,
            params Expression<func<object,string>>[] source)
        {
            Dictionary objectValyeDictionary = new Dictionary();
            foreach (var src in source)
            {
                var keyValue = obj.AsKeyValuePair(src);
                if(!objectValyeDictionary.ContainsKey(keyValue.Key))
                    objectValyeDictionary.Add(keyValue.Key, keyValue.Value);
            }

            return objectValyeDictionary;
        }

Helper Fucntion For Property Name


The below helper method is use to extract the property name from lambda expression


        public static KeyValuePair AsKeyValuePair(this object obj, Expression<func<object, tproperty>> propertyLambda)
        {
            var me = propertyLambda.Body as MemberExpression;
            UnaryExpression ue;
            if (me == null)
            {
                ue = propertyLambda.Body as UnaryExpression;

                if(ue == null)
                    throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");

                me = (MemberExpression) ue.Operand;
            }

            string memberName = me.Member.Name;
            var value = obj.GetType().GetProperty(memberName).GetValue(obj, null);
            return new KeyValuePair(me.Member.Name, value);
        }

No comments:

Post a Comment