Sorting in Asp.Net Web API (Rest API)

In this article, we discuss how to provide the sorted response to the client based on the given sore expression in Asp.Net Web API. Here we create the simple Sort extension method to sort the final response based on input.

To apply the sorting dynamically, we need to install System.Linq.Dynamic package through NuGet. Install System.Linq.Dynamic package and create extension method SortSource(), as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;

namespace CompanyRestAPI.Helper
{
    /// <summary>
    /// Public class for Extension methods
    /// </summary>
    public static class Extensions
    {

        /// <summary>
        /// It sorts the given source based on given sortExpression
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sortExpression"></param>
        /// <returns></returns>
        public static List<T> SortSource<T>(this List<T> source, string sortExpression)
        {
            if (source == null || sortExpression == null)
            {
                throw new ArgumentNullException();
            }


            var list = sortExpression.Split(',');

            string finalSortExpression = string.Empty;

            foreach (string column in list)
            {
                if (column.StartsWith("-"))
                {
                    finalSortExpression = finalSortExpression + column.Remove(0, 1) + " desc,";
                }
                else
                {
                    finalSortExpression = finalSortExpression + column + ",";
                }
            }

            if (string.IsNullOrEmpty(finalSortExpression) == false)
            {
                source = source.OrderBy(finalSortExpression.Remove(finalSortExpression.Count() - 1)).ToList<T>();
            }

            return source;
        }
    }
}

SortSource() method sorts the given source based on sortExpression provided. We can provide multiple fields here to sort the source either in ascending or descending order. If sort field has minus(-) prefix, it sorts it in descending order otherwise in ascending order. For example, if we provide sortExpression=id,-name; SortSource() method sorts the source first by id ascending order then by name descending order.

Let’s use this SortSource() extension method in our getemployees API method as shown below.

using CompanyRestAPI.App_Start;
using CompanyRestAPI.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CompanyRestAPI.Helper;

namespace CompanyRestAPI.Controllers
{
    /// <summary>
    /// Employees Controller
    /// </summary>
    public class EmployeesController : ApiController
    {
        /// <summary>
        /// Get all employees
        /// </summary>
        /// <returns></returns>
        // GET: Employees
        [Route("api/employees/getemployees")]
        [HttpGet]
        //[BasicAuthentication]
        public HttpResponseMessage GetEmployees(string sortExpression = "id")
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees().SortSource(sortExpression));
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }      
    }
}

As shown above, we are applying the SortSource extension method on final response before returning it to the client; if the client doesn’t pass any sort expression, GetEmployees() API method sorts based on id by default.

Run the API and send the request through the Fiddler tool, as shown below.

Here we are sending the request, including sort expression as “-name”. That means asking API to return the data by sorting the name field in descending order; Fiddler displays the result as shown below.

Download the API code from GitHub at https://github.com/techinfocorner/CompanyRestAPI.