How to Sort a Generic List in C#

No.of Views3766
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  21 Sep 2010 09:09:27
Tag : CSharp , Miscellaneous
This article will give code snippet on how to sort a generic list in C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

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, 

Image Loading

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  

Image Loading

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 

Image Loading

Step 3

Pass the compare function as parameter of sort method.

Image Loading

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

CompareProduct.cs

class CompareProduct : IComparer<Product>
    {publicint 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> Membersint 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

Image Loading
 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
By:RRaveenDate Of Posted:12/29/2010 11:54:26 AM
The Answer
Hi, Please refer this article to do your custom sort. http://www.codegain.com/articles/dotnetframeworks/general/how-to-sort-arraylist-with-custom-objects-in-csharp-or-vbnet.aspx
By:limhiDate Of Posted:11/18/2010 3:34:32 PM
quicksort
hi, I have a quick quesiton, I?ve been trying to make a program to sort a list of names and lastnames in aplphabetical order but I havent been able to, can you give a hint on how to do it?, thank you
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top