Thursday, 22 November 2012

Dynamic Sort Object

In the development it is always require to sort grids that has dynamic data source. Here is the code to sort with any property of object that is generic type.

/* Pass object to sort */
  public static List<T> DynamicSort<T>(List<T> genericList, string sortExpression, string sortDirection)
        {
            if (genericList != null)
            {
                int sortReverser = sortDirection.ToLower().StartsWith("asc") ? 1 : -1;

                Comparison<T> comparisonDelegate =
                    new Comparison<T>(delegate(T x, T y)
                    {
                        MethodInfo compareToMethod = GetCompareToMethod<T>(x, sortExpression);

                        object xSortExpressionValue = x.GetType().GetProperty(sortExpression).GetValue(x, null);
                        object ySortExpressionValue = y.GetType().GetProperty(sortExpression).GetValue(y, null);
                        object result = compareToMethod.Invoke(xSortExpressionValue, new object[] { ySortExpressionValue });
                        return sortReverser * Convert.ToInt16(result);
                    });

                genericList.Sort(comparisonDelegate);
            }
            return genericList;
        }

/* Get compare to method */
        public static MethodInfo GetCompareToMethod<T>(T genericInstance, string sortExpression)
        {
            Type genericType = genericInstance.GetType();
            object sortExpressionValue = genericType.GetProperty(sortExpression).GetValue(genericInstance, null);
            Type sortExpressionType = sortExpressionValue.GetType();
            MethodInfo compareToMethodOfSortExpressionType = sortExpressionType.GetMethod("CompareTo", new Type[] { sortExpressionType });

            return compareToMethodOfSortExpressionType;
        }

No comments:

Post a Comment