.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Sorting a Generic List in C#

Posted By:Dhananjay Kumar       Posted Date: September 17, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

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

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 prdList = new List()
            {
                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,



 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
2.  Define the compare function. Give sorting logic here.
3.  Pass the compare function as the parameter of sort method of list.

Step 1

 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



Step 3

Pass the compare function as parameter of sort method.

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

CompareProduct.cs

class CompareProduct : IComparer
    {

        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 Members

         int IComparer.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 prdList = new List();
            CompareProduct compare = new CompareProduct();
            List prdList = new List()
            {
               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




 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend