Dynamically Sorting Object at Runtime Using Reflection C#


First of all I like to thank my colleague. Because I learned of this through my colleague Venkatesh. Thank for this man.

Step 1: How it is useful ?

  1. You can sort the object based on the URL parameter.
  2. You can sort the object at runtime.
  3. You can sort both asc and desc at runtime.
  4. Property can be passed as string to sort the object.
  5. Absolutely sorting at runtime.
  6. Reduced a lot of code.
  7. It is written in the generic way to reuse it.

Step 2: Sorting Mechanism

  1. Ascending
  2. Descending

Step 3: Used Namespaces

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;

Step 4: Usage of dynamic sorting

protected void Page_Load(object sender, EventArgs e)
{
    SortStudents();
}

Step 5: Sorting Dynamically based on the object property

private void SortStudents()
{
    Students students = new Students();

    //add the student to the list
    students.Add(new Student("Tom", 83));
    students.Add(new Student("Joe", 86.4));
    students.Add(new Student("Rudy", 85));
    students.Add(new Student("Chris", 87.2));

    //Sorting by its name dynamically.
    students = (Students)DynamicSort1<Student>(students, "Name", "asc");
    students.Print();

    //Sorting by its grade dynamically.
    students = (Students)DynamicSort1<Student>(students, "Grade", "desc");
    students.Print();

}

Step 6: Getting Comparer method using reflection

        /// <summary>
        /// Used to get method information using refection
        /// </summary>
        private 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;
        }


Step 7: Generic Dynamic Sorting mechanism

        private static List<T> DynamicSort1<T>(List<T> genericList, string sortExpression, string sortDirection)
        {
            int sortReverser = sortDirection.ToLower().StartsWith("asc") ? 1 : -1;

            Comparison<T> comparisonDelegate =
            new Comparison<T>(delegate(T x, T y)
            {
                //Just to get the compare method info to compare the values.
                MethodInfo compareToMethod = GetCompareToMethod<T>(x, sortExpression);

                //Getting current object value.
                object xSortExpressionValue = x.GetType().GetProperty(sortExpression).GetValue(x, null);

                //Getting the previous value.
                object ySortExpressionValue = y.GetType().GetProperty(sortExpression).GetValue(y, null);

                //Comparing the current and next object value of collection.
                object result = compareToMethod.Invoke(xSortExpressionValue, new object[] { ySortExpressionValue });

                // result tells whether the compared object is equal,greater,lesser.
                return sortReverser * Convert.ToInt16(result);
            }); 

            //here we using the comparison delegate to sort the object by its property
            genericList.Sort(comparisonDelegate);
 
            return genericList;
        }


Step 8: Output of using NAME property of Student

RefCsharp1.jpg

Step 9: Output of using GRADE property of Student

RefCsharp2.jpg

Thanks for reading this article.