LINQ Dynamic OrderBy Example C# .Net
Let’s say we have a front-end web application where we want to display the data in the form of a table. To help us organize and process the data we would want to be able to sort the data dynamically by each column. So, how we would design an API that could accomplish those tasks?
In this article, I want to guide you in the process of how to design an API that could accomplish the task and how you can implement it in your .NET API very simply by adding a few lines that shouldn’t take you more than 5 minutes.
Here is the Sample c# code, please note: no need Dynamic.linq.core
Sample Class Objects:
//// Data Class
public class EmployeeList
{
public Long EmpID {get;set;}
public string Name {get;set;}
public string Department {get;set;}
public string Designation {get;set;}
public string ReportingTo {get;set;}
public DateTime DOB {get;set;}
public string Gender {get;set;}
}
//// API request class
public class FilterRequest
{
public string SearchKeyword {get;set;}
public string SortBy {get;set;}
public string SortOrder {get;set;}
}
Dynamic Sorting C#:
//// Sample Request
request.SortBy="Designation";
request.SortOrder="DESC";
//// Employee list object (db result)
List lstEmp=new();
//// Dynamic Sorting using LINQ (without any dynamic.linq
var propertyInfo = typeof(EmployeeList).GetProperty(request.SortBy.Trim(), BindingFlags.SetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null)
{
if (request.SortOrder == "DESC")
{
lstEmp = lstEmp.OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList();
}
else
{
lstEmp = lstEmp.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();
}
}
else
{
lstEmp = lstEmp.OrderByDescending(t => t.EmpID).ToList();
}