Saturday 21 January 2012

Sorting a Generic List in C#


CSharp, Miscellaneous

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,
clip_image002
What we are going to do here is that, first we will sort the list in productprice and then group they and then we will sort them on 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
clip_image004
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
clip_image006
Step 3
Pass the compare function as parameter of sort method.
clip_image007
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;
        }
Now we need to use ProductCompare class to sort the list as of our requirement.
Program.cs



namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {
            int tempPrevious = 0;
            int tempcurrent = 0;
            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


clip_image009 



Posted by September 17, 2010 1 Comment

No comments :