Sorting a Generic List in C#


Objective 

This article will give code snippet on how to sort a generic list in C# 

I have a class called Product 

Product.cs

class Product
{
    public string ProductName { get; set; }
    public int ProductPrice { get; set; }
}

And List of Product as below, 

List<Product> prdList = new List<Product>()
{
    new Product {ProductName = "Apple",ProductPrice = 101},
    new Product {ProductName = "Apple",ProductPrice = 99},
    new Product {ProductName = "Pen",ProductPrice = 99},
    new Product {ProductName = "Pencil", ProductPrice = 100},
    new Product {ProductName ="Apple", ProductPrice = 100},
    new Product { ProductName = "Mango", ProductPrice = 35},
    new Product {ProductName = "Shirt", ProductPrice=200}
}; 

Now we need to sort the above generic list in ascending order. 
  1. On ProductPrice 
  2. And then  on ProductName 
So our expected output would be something like, 

1.gif
 
What we are going to do here is that, first we will sort the list by ProductPrice and within ProductPrice by ProductName

Steps are as follows 
  1. Create a class and implement IComparer<T> 
  2. Define the compare function. Give sorting logic here. 
  3. Pass the compare function as the parameter of sort method of list. 
Step 1 

2.gif
 
Here Product is the class we are going to sort.  You are free to give any name of the class. 

Step 2

Define compare function 

3.gif
 
Step 3 

Pass the compare function as parameter of sort method. 

4.gif
 
Here prdList is generic list of Product.  And compare is object of class CompareProduct.

CompareProduct.cs 

class CompareProduct : IComparer<Product>
{
    public   int Compare(  Product p1,   Product p2)
    {
        int result;
        if (Product.ReferenceEquals(p1, p2))
        {
            result = 0;
        }
        else
        {
            if (p1 == null)
            {
                result = 1;
            }
            else if (p2 == null)
            {
                result = -1;
            }
            else
            {
                result = NumberCompare(p1.ProductPrice, p2.ProductPrice);
                //result = StringCompare(p1.ProductName, p2.ProductName);
                if (result == 0)
                {
                    // result = NumberCompare(p1.ProductPrice, p2.ProductPrice);
                    result = StringCompare(p1.ProductName, p2.ProductName);
                }
            }
        }
        return result;
    }
    int StringCompare(string strFirstString, string secondString)
    {
        int result;
        if (strFirstString == null)
        {
            if (secondString == null)
            {
                result = 0;
            }
            else
            {
                result = 1;
            }
        }
        else
        {
            result = strFirstString.CompareTo(secondString);
        }
        return result;
    }
    int NumberCompare(int number1, int number2)
    {
        int result;
        if (number1 > number2)
        {
            result = 1;
        }
        else if (number1 < number2)
        {
            result = -1;
        }
        else
        {
            result = 0;
        }
        return result;
    }
    #region IComparer<Product> Members
    int IComparer<Product>.Compare(Product x, Product y)
    {
         throw new NotImplementedException();
    }
    #endregion
}

Now we need to use ProductCompare class to sort the list as of our requirement. 

Program.cs

class Program
{
    static void Main(string[] args)
    {
        int tempPrevious = 0;
        int tempcurrent = 0;
        //  List<Product> prdList = new List<Product>();
        CompareProduct compare = new CompareProduct();
        List<Product> prdList = new List<Product>()
        {
           new Product {ProductName = "Apple",ProductPrice = 101},
           new Product {ProductName = "Apple",ProductPrice = 99},
           new Product {ProductName = "Pen",ProductPrice = 99},
           new Product {ProductName = "Pencil", ProductPrice = 100},
           new Product {ProductName ="Apple", ProductPrice = 100},
           new Product { ProductName = "Mango", ProductPrice = 35},
           new Product {ProductName = "Shirt", ProductPrice=200}
        };
        prdList.Sort(compare.Compare);
        foreach (Product p in prdList)
        {
            tempcurrent = p.ProductPrice;
            if (tempcurrent != tempPrevious)
            {
                Console.WriteLine("**********************");
                Console.WriteLine("Price = "+ p.ProductPrice);
            }
            Console.WriteLine(p.ProductName);
            tempPrevious = p.ProductPrice;
        }
        Console.ReadKey(true);
    }
}

When we run output would be 

5.gif

Similar Articles