Sorting a List in ASC/DESC order using LINQ

Most of the developers are unaware of the capabilities of .NET 3.5 and above. Still going for old way of sorting calling List.Sort and implementing a delegate or lambda expression to specify the sort expression.  But the slight problem is what you will do for “ASCENDING”  and “DESCENDING” order sorting. You have to specify the delegate logic for sorting in Ascending and another logic for sorting in descending order.

I am providing you some sample code to give a clear picture. The sample code consists of the following and also read through the inline comments in the code.

Sample Code 1 : Sorting using List.Sort and delegate function to implement the comparison logic.

Sample Code 2 : Sorting using Linq 2 Objects => “OrderBy” and “OrderByDescending()” extension methods.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using WebApplication1;

namespace WebApplication1
{
    /// <summary>
    /// 
    /// </summary>
    public class CustomerTest
    {

        public void TestCustomerSort()
        {

            //Normal way using delegates or lambda expression and custom sorting logic. 

            List<Customer> normalSortASC = GetCustomerSortedNormalWay(SortDir.ASC);

            List<Customer> normalSortDESC = GetCustomerSortedNormalWay(SortDir.DESC);

            //LINQ way.. LinQ does sorting for you, just utilize the LinQ-2-Objects classes firmly that's all. 
            List<Customer> linqSortASC = GetCustomerSortedLinqWay(SortDir.ASC);

            List<Customer> linqSortDESC = GetCustomerSortedLinqWay(SortDir.DESC);

            HttpContext.Current.Response.Write("Test Success");
        }

        /// <summary>
        /// Gets the dummy customer data.
        /// </summary>
        /// <returns></returns>
        public List<Customer> GetDummyCustomerData()
        {
             List<Customer> customers = new List<Customer>();

            customers.Add(new Customer()
                              {
                                  CustomerID =  "CA1",
                                  ContactName =  "Alpha"
                              });

            customers.Add(new Customer()
            {
                CustomerID = "AA3",
                ContactName = "Beta"
            });

            customers.Add(new Customer()
            {
                CustomerID = "AA1",
                ContactName = "Gamma"
            });


            customers.Add(new Customer()
            {
                CustomerID = "A11",
                ContactName = "Zetta"
            });

            return customers;
        }

        /// <summary>
        /// Gets the customer sorted normal way.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns></returns>
        public List<Customer> GetCustomerSortedNormalWay(SortDir order)
        {
            List<Customer> customers = GetDummyCustomerData();

             switch(order)
             {
                 case SortDir.ASC:
                     customers.Sort(delegate(Customer a, Customer b)
                                                    {
                                                        return a.CustomerID.CompareTo(b.CustomerID);
                                                    });
                     
                      //---OR --- Using lambda expression like this.  

                     customers.Sort((a, b) => a.CustomerID.CompareTo(b.CustomerID)); //awkward isn't it. need to specify the two objects to compare against a

                     break;

                 case SortDir.DESC:
                     customers.Sort(delegate(Customer a, Customer b)
                     {
                         return b.CustomerID.CompareTo(a.CustomerID); // Reversing the sort based on "b"
                     });

                     //---OR --- Using lambda expression like this.  

                     customers.Sort((a, b) => b.CustomerID.CompareTo(a.CustomerID)); //awkward isn't it. need to specify the two objects to compare against and reverse the comparison logic. not looking good and confusing. 

                     break;


                 default:
                     customers = GetCustomerSortedNormalWay(SortDir.ASC);
                     break;
             }


            return customers;
        }



        /// <summary>
        /// Gets the customer sorted LINQ way.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns></returns>
        public List<Customer> GetCustomerSortedLinqWay(SortDir order)
        {
            List<Customer> customers = GetDummyCustomerData();

            switch (order)
            {
                case SortDir.ASC:
                    customers = (customers.OrderBy(c => c.CustomerID)).ToList(); // Just a simple line. Specifying just specify sort key as "CustomerID", and linq does the fancy sorting for you.

                    break;

                case SortDir.DESC:
                    customers = (customers.OrderByDescending(c => c.CustomerID)).ToList(); // Just a simple line ca;; "OrderByDescending" and just specify sort key as "CustomerID", and linq does the fancy sorting for you.
                    break;


                default:
                    customers = GetCustomerSortedNormalWay(SortDir.ASC);
                    break;
            }


            return customers;
        }

    }

    /// <summary>
    /// Sort Direction - Enum dictionary
    /// </summary>
    public enum SortDir
    {
        ASC,
        DESC,
        Default 
    }
}

 

My intension with the post is not saying that still following old ways of sorting is bad. But just to let you remind you about the alternative ways of doing it in .NET 3.5 and .NET 4.0.  If newer .NET frameworks have a better way of doing it, why don’t we utilize that and increase our productivity.

Using linq2Objects saves our precious time as well and number of lines we write also minimized and helps us in managing the source code in more better way.

 

Hope this is helpful for the needed..

Other times, you're doing some piece of work and suddenly you get feedback that tells you that you have touched something that is very alive in the cosmos. Share your feedback on this blog, it will help me improve it a lot..