Showing posts with label Func. Show all posts
Showing posts with label Func. Show all posts

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);
        }

Saturday, September 24, 2016

Generic Comparer for DistinctBy Using Func and IComparer For IEnumerable

During development of many projects, I have been come across to develop IComparer for different reasons and situations. Each time creating new comparer for different classes. Therefore, I have found solution to use single generic Comparer for all the IEnumerable extension which requires IComparer for the class.

I have used DistinctBy Example to go throw the Generic Extension Method.



 public static class Compare
    {
        public static IEnumerable<T> DistinctBy<T, TIdentity>(this IEnumerable<T> source, Func<T, TIdentity> identitySelector)
        {
            return source.Distinct(Compare.By(identitySelector));
        }

        public static IEqualityComparer<TSource> By<TSource, TIdentity>(Func<TSource, TIdentity> identitySelector)
        {
            return new DelegateComparer<TSource, TIdentity>(identitySelector);
        }

        private class DelegateComparer<T, TIdentity> : IEqualityComparer<T>
        {
            private readonly Func<T, TIdentity> identitySelector;

            public DelegateComparer(Func<T, TIdentity> identitySelector)
            {
                this.identitySelector = identitySelector;
            }

            public bool Equals(T x, T y)
            {
                return Equals(identitySelector(x), identitySelector(y));
            }

            public int GetHashCode(T obj)
            {
                return identitySelector(obj).GetHashCode();
            }
        }
    }

DistinctBy Extension Method


The function simply creates an extension method for IEnumerable together with Func with input of Type and outputting property of type TIdentity.

Using this way any class can provide the property that needs to be used for comparing and calculating hashcode for that property. However, TIdentity usually will be the unique key for the class object.

IEqualityComparer

This function simply create and object of Comparer passing in the Func delegate. The resulting DelegateComparer will use the Func Delegate to fetch the unique property and compare the unique property and calculate the hashcode.

Usage


public class AClass
{
  public string AProperty {get; set;}
}

public IEnumerable<AClass> DistinctAClass(IEnumerable<AClass> aClassList)
{
    aClassList.DistinctBy(a => a.AProperty);
}


Hope this helps to create unnecessary classes for comparer.