Dynamically Sorting Object At Runtime Using Reflection C#

Introduction

First of all, I would like to thank my colleague because I learned of this through my colleague Venkatesh. Thank you for this man.

Step 1. How is it useful?

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

Step 2. What is a Sorting Mechanism?

Sorting is a fundamental operation in computer science and programming, crucial for organizing and retrieving data efficiently. Here's an overview of sorting mechanisms commonly used in programming.

  1. Ascending
  2. Descending

Step 3. Namespaces Used

Namespaces in programming languages like C# and Java provide a way to organize and manage code. They serve as containers for classes, interfaces, structures, enumerations, and delegates, helping avoid naming conflicts and providing a clear hierarchical structure to the codebase.

Example

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

Step 4. How to use Dynamic sorting?

Dynamic sorting is a powerful technique in programming, especially in scenarios where you want to sort data based on user input or runtime conditions. Here are some common scenarios and use cases where dynamic sorting is highly beneficial.

Example

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

Step 5. Sorting Dynamically based on the object property

Sorting dynamically based on object properties is a common requirement in programming. This technique allows developers to sort a collection of objects based on a specific property, which could be a string, number, date, or any other data type. Here's how you can sort a list of objects dynamically in C# based on their properties.

Example

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

    // Add students 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 name dynamically.
    students = (Students)DynamicSort1<Student>(students, "Name", "asc");
    students.Print();
    // Sorting by grade dynamically.
    students = (Students)DynamicSort1<Student>(students, "Grade", "desc");
    students.Print();
}

Step 6. Getting Comparer method using reflection

Getting a comparison method using reflection is a common task when you need to sort objects based on dynamically provided properties. Reflection allows you to inspect and invoke methods dynamically at runtime.

Example

/// <summary>
/// Used to get method information using reflection
/// </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.  What is the Generic Dynamic Sorting mechanism?

Generic dynamic sorting is a technique in programming where you can sort a collection of objects based on different properties at runtime. Generics allow you to create classes, interfaces, methods, or delegates with a placeholder for the data type. By using generics, you can create a flexible sorting mechanism that works with various types of objects.

 Example. Here's an example of a 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>((x, 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, or lesser.
        return sortReverser * Convert.ToInt16(result);
    });
    // Using the comparison delegate to sort the object by its property.
    genericList.Sort(comparisonDelegate);

    return genericList;
}

Output using the NAME property of the Student

RefCsharp1.

Output of using GRADE property of Student

RefCsharp2

Thanks for reading this article.


Similar Articles