Wednesday 14 October 2015

Dynamic Sorting for WebAPI Get method

We can sort results which returns from a WebAPI Get method using Linq Dynamics as follows.

First of all we need to create an extension method for IQueryable<T>. This method would perform required sorting. Following is the code.


 
public static class IQueryableExtensions
    {
        public static IQueryable<T> ApplySort<T>(this IQueryable<T> source, string sort)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (sort == null)
            {
                return source;
            }

           var lstSort = sort.Split(',');

      
            string completeSortExpression = "";
            foreach (var sortOption in lstSort)
            {
           
                if (sortOption.StartsWith("-"))
                {
                    completeSortExpression = completeSortExpression + sortOption.Remove(0, 1) + " descending,";
                }
                else
                {
                    completeSortExpression = completeSortExpression + sortOption + ",";
                }

            }

            if (!string.IsNullOrWhiteSpace(completeSortExpression))
            {
                source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
            }

            return source;
        }
    }


We have hard coded the separator and treat the - sign as the descending sorter. source.OrderBy is using the linq dynamics OrderBy method.
Application of the sorting can be done as follows.

 
[HttpGet, Route("ByClient/{clientID:int}")]
public IHttpActionResult GetByClient(int clientID,string sort="id")
{
     try
      {
          var receivedModel = VehicleProvider.GetByClient(clientID);
          IHttpActionResult response = Ok(receivedModel.ApplySort(sort));
          return response;
      }
      catch (Exception)
      {
          return InternalServerError();
      }
     
}


The VehicleProvider.GetByClient method should return an IQueryable<T>. All we need to do is plug the ApplySort method with sort parameters to the result.

No comments:

Post a Comment