Create Dynamic Sorting in Your .NET API in 5 minutes

Jonathan Kristanto
Bina Nusantara IT Division
4 min readJun 30, 2023
Photo by Edu Grande on Unsplash

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.

#1: The Case

The first, is to design the API request & response. In this example, I will use JSON Body as a payload. Let’s take a look at the table format we have :

Image by Author

We have 4 columns of data to show. We also need to have the ability to paginate our data. By analyzing the requirement, here’s the API request & response design I have :

Request Body :
{
"page": int,
"take": int,
"orderBy": string [column name],
"orderType": asc / desc
}
Response Body : 
{
"data": [
{
"featureID": ID,
"featureName": string,
"featureType": string,
"createdBy": string [username],
"createdAt": datetime
},
.....
],
"totalPage": int
"errorMessage" : string
}

I won’t go into too much detail on how to create the endpoint, process the result, and return it to the user since you will have your own design pattern to do it. I want to focus on the part on how you receive the “orderBy” and “orderType” parameters and use it to enable dynamic sorting.

#2: The Naive Solution

Usually in C# when we want to sort our data we will use LINQ. We might use a LINQ query like this :

var temp = new List<FeatureResponseDTO>();

if (req.OrderBy.ToLower() == "featurename")
temp = query.OrderBy(x => x.FeatureName).ToList();
else if (req.OrderBy.ToLower() == "featuretype")
temp = query.OrderBy(x => x.FeatureType).ToList();
else if (req.OrderBy.ToLower() == "createdby")
temp = query.OrderBy(x => x.CreatedBy).ToList();
else if (req.OrderBy.ToLower() == "createdat")
temp = query.OrderBy(x => x.CreatedAt).ToList();

var response = temp.Skip((page - 1) * take).Take(take).ToList();

This query will work but look at all the custom handling we have to make and the maze of if-else statements. We haven’t even made the condition where we need to do ascending or descending sorting. Ugh.. imagine if need 10 more columns you need to sort. This will make a tedious copy-paste job, makes your code dirty & likely to introduce bugs.

#3: The Efficient Solution

Now let me introduce you to the Dynamic LINQ Library. Up until June 2023 when this article is written, the library is widely used with 105M downloads & supported by Microsoft too.

With this library, you can use string values to order your data. The syntax mimics the way SQL query to order your data. ORDER BY [PROPERTY NAME] ASC|DESC

To install this package System.Linq.Dynamic.Core by running this in the Package Manager Console / via Manage Nuget Solution in Visual Studio

Install-Package System.Linq.Dynamic.Core
Visual Studio Nuget Package Manager GUI by Author

Then you add this using clause:

using System.Linq.Dynamic.Core;

Your code will look like this:


dynamic response;
if (req.OrderType == "desc")
{
response = query.OrderBy(req.OrderBy + " desc").Skip((page - 1) * take).Take(take).ToList();
}
else if(req.OrderType == "asc" || req.OrderType == null || req.OrderType == "")
{
response = query.OrderBy(req.OrderBy + " asc").Skip((page - 1) * take).Take(take).ToList();
}
else
{
throw new Exception("Order Type must be 'asc' or 'desc' ");
}

Here we could use pass the parameter “OrderBy” from the request to sort the data. This way we also only need 2 conditional statements to check the “OrderType” is ascending or descending with the last one being for error handling.

--

--