CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Sorting in C# Generic List(List)

By Satheesh babu
Posted On Jun 20,2008
Article Rating:
Be first to rate
this article.
No of Comments: 9
Category: C#
Print this article.

Sorting in C# Generic List(List<T>)

Introduction

It is obvious that when we are working on business objects or Entities in our application, we will need its corresponding collections. In 1.x days, we use ArrayList for creating a collection of object or entity. We can also create our own custom collection by inheriting the Arraylist or CollectionBase in those times. The main disadvantage of using ArrayList is that it can hold any type of objects, which can cause some serious issues where a collection of similar objects are expected. This is the right place in 1.x to go for our own collection by inheriting the Arraylist or CollectionBase. With the introduction of 2.0 framework, we got so many new useful features that make our development simple. Generic list is one of such feature which we can use for creating a collection of similar objects.

We can create our collection with generic List<T>, where T can be our BO, which can be strongly typed. For example, List<Employee> will allow only Employee instance to be added to the list. Moving forward we will see how to implement sort to using generic list Sort overload methods in this article.

Things to Consider:

To make things easily understandable, I will use Customer object with Name and Age attributes as seen in Listing 1.

 

Listing 1 - Customer BO

class Customer

    {

        private int _Age;

        private string _Name;

 

        public int Age

        {

            get { return _Age; }

            set { _Age = value; }

        }

        public string Name

        {

            get { return _Name; }

            set { _Name = value; }

        }

    }

 

So the Generic list that can take Cutomer object can be defined as,

Listing 2 - Customer BO Generic List

List<Customer> cuslist = new List<Customer>();

 

How to sort a Generic List (List<T>)?

To sort the collection, generic list provides sort method with 4 overloads,

Listing 2 - Generic List Sort Methods

List.Sort ()

List.Sort (Generic Comparison)

List.Sort (Generic IComparer)

List.Sort (Int32, Int32, Generic IComparer)

 

In the coming sections of this article we will see the implementation of sort in generic list using the above 4 overloads.

 

1st Overload - List.Sort ()

This method will sort the members of the list using the default comparer that is implemented in the object. I would like to sort based on the name in Customers List.

To make this method to work Customer BO should inherit IComparable<Customer> and implement public int CompareTo(Customer  cus) method. So our final BO will look like,

 

Listing 3 - List.Sort () Implementation

class Customer : IComparable<Customer>

    {

        //Members

        //1st Overload

        public int CompareTo(Customer cus)

        {

            return this.Name.CompareTo(cus.Name);

        }

    }

Consider,

 

Listing 4 - List creation and Sorting

          

      List<Customer> cuslist1 = new List<Customer>();

            Customer cus1 = new Customer();

            cus1.Name = "Fatima";

            cus1.Age = 23;

            cuslist1.Add(cus1);

 

            Customer cus2 = new Customer();

            cus2.Name = "Evangeline";

            cus2.Age = 24;

            cuslist1.Add(cus2);

 

            Customer cus3 = new Customer();

            cus3.Name = "Damien";

            cus3.Age = 27;

            cuslist1.Add(cus3);

 

            Customer cus4 = new Customer();

            cus4.Name = "Cameroon";

            cus4.Age = 21;

            cuslist1.Add(cus4);

 

            Customer cus5 = new Customer();

            cus5.Name = "Babu";

            cus5.Age = 20;

            cuslist1.Add(cus5);      

           

            cuslist1.Sort();

            foreach (Customer cus in cuslist1)

            {

                Console.WriteLine(cus.Name + " " + cus.Age);

            }

 

The out put of the above code will be,

 

OUTPUT:

Babu 20

Cameroon 21

Damien 27

Evangeline 24

Fatima 23

 

2nd Overload - List.Sort (Generic Comparison)

The argument “Generic Comparison” is the Comparsion<T> delegate called Comparison Generic Delegate.

To understand the implementation of this overload method we should understand the generic comparison delegate first. The signature of the delegate is,

 

Listing 5 - List.Sort (Generic Comparison) syntax

 

public delegate int Comparison<T> (

       T x,

       T y

)

To implement this sort method we should define a method with the above signature that compares the 2 objects and returns an integer value. Usage of this generic delegate to sort will prevent the need to inherit the BO with IComparable<T> interface. Refer msdn about the delegate here.

 

Consider, Customer BO in the section Things to Consider.

 

Here I am going to implement 2 sort methods with Generic Comparison Delegate’s signature, one for sort by name and the other for sort by Age. Here comes the implementation.

So our final BO will look like,

 

Listing 6 - Customer BO with Generic Comparison delegate

class Customer

    {

       //Members

      

         public static int CompareCustomerName(Customer c1, Customer c2)

        {

            return c1.Name.CompareTo(c2.Name);

        }

        public static int CompareCustomerAge(Customer c1, Customer c2)

        {

            return c1.Age.CompareTo(c2.Age);

        }

 

}

 

How to use it?

To use the List.Sort(Generic Comparison) create a instance of Comparison<Customer> delegate and register it with CompareCustomerName and CompareCustomerAge  method like below,

 

Listing 7 - List creation and Sorting

 

            List<Customer> cuslist2 = new List<Customer>();

 

            cus1 = new Customer();

            cus1.Name = "Tom";

            cus1.Age = 23;

            cuslist2.Add(cus1);

 

            cus2 = new Customer();

            cus2.Name = "Sanjay";

            cus2.Age = 24;

            cuslist2.Add(cus2);

 

            cus3 = new Customer();

            cus3.Name = "Mathew";

            cus3.Age = 27;

            cuslist2.Add(cus3);

 

            cus4 = new Customer();

            cus4.Name = "Nguyen";

            cus4.Age = 21;

            cuslist2.Add(cus4);

 

            cus5 = new Customer();

            cus5.Name = "Peter";

            cus5.Age = 20;

            cuslist2.Add(cus5);

 

            Console.WriteLine("\nSort Based on Name");

            Comparison<Customer> compnamedel = new Comparison<Customer>(Customer.CompareCustomerName);

            cuslist2.Sort(compnamedel);

 

            foreach (Customer cus in cuslist2)

            {

                Console.WriteLine(cus.Name + " " + cus.Age);

            }

 

            Console.WriteLine("\nSort Based on Age");

            Comparison<Customer> compagedel = new Comparison<Customer>(Customer.CompareCustomerAge);

            cuslist2.Sort(compagedel);

 

            foreach (Customer cus in cuslist2)

            {

                Console.WriteLine(cus.Name + " " + cus.Age);

            }

 

The output will be,

 

OUTPUT:

Sort Based on Name

Mathew 27

Nguyen 21

Peter 20

Sanjay 24

Tom 23

 

Sort Based on Age

Peter 20

Nguyen 21

Tom 23

Sanjay 24

Mathew 27

 




3rd Overload - List.Sort (Generic IComparer)

The signature of the method is,

 

Listing 8 - - List.Sort (Generic IComparer) syntax

 List.Sort (Generic IComparer)

 

This method sorts the generic list with the compare given in argument.

To implement the comparer implement IComparer<T> interface in a separate class like,

 

Listing 9 - - List.Sort (Generic IComparer) implementation

class CustomerNameSort : IComparer<Customer>

    {

        public int Compare(Customer c1, Customer c2)

        {

            return c1.Name.CompareTo(c2.Name);

        }

    }

 

i.e implement Compare() method as above to sort customers list based on name.

 

Usage:

Listing 10 - List creation and Sorting

     List<Customer> cuslist3 = new List<Customer>();

            cus1 = new Customer();

            cus1.Name = "Louise";

            cus1.Age = 23;

            cuslist3.Add(cus1);

 

            cus2 = new Customer();

            cus2.Name = "Katie";

            cus2.Age = 24;

            cuslist3.Add(cus2);

 

            cus3 = new Customer();

            cus3.Name = "Viru";

            cus3.Age = 27;

            cuslist3.Add(cus3);

 

            cus4 = new Customer();

            cus4.Name = "Satheesh";

            cus4.Age = 21;

            cuslist3.Add(cus4);

 

            cus5 = new Customer();

            cus5.Name = "Naveen";

            cus5.Age = 20;

            cuslist3.Add(cus5);

 

            Console.WriteLine("\nSort Based on Name");

            CustomerNameSort esort = new CustomerNameSort();

            cuslist3.Sort(esort);

 

            foreach (Customer cus in cuslist3)

            {

                Console.WriteLine(cus.Name + " " + cus.Age);

            }

 

The output will be,

 

OUTPUT:

Sort Based on Name

Katie 24

Louise 23

Naveen 20

Satheesh 21

Viru 27

 

4th Overload - List.Sort (Int32, Int32, Generic IComparer)

The fourth generic overload sort method will be helpful when we like to sort our list with a range specified, i.e we can say to sort a subset of the list. The syntax will be like,

 

Listing 11 - List.Sort (Int32, Int32, Generic IComparer) Syntax

List.Sort (Int32, Int32, Generic IComparer)

 

The first argument will be the start position, the next argument is number of element to be sorted starting from start position specified and the last is comparer to use.

To make this sort method to work we need to implement IComparer interface as we did in 3rd Overload - List.Sort (Generic IComparer) section.

 The comparer for our Customer BO will be,

 

Listing 12 - IComparer<Customer> implementation

class CustomerNameSort : IComparer<Customer>

    {

        public int Compare(Customer c1, Customer c2)

        {

            return c1.Name.CompareTo(c2.Name);

        }

    }

 

Usage:

I am creating a unsorted Customer list with length 5 as shown below and it is sorted by name using the generic list sort.

 

Listing 13 - List creation and Sorting

 

      List<Customer> cuslist4 = new List<Customer>();

            cus1 = new Customer();

            cus1.Name = "George";

            cus1.Age = 23;

            cuslist4.Add(cus1);

 

            cus2 = new Customer();

            cus2.Name = "Bush";

            cus2.Age = 24;

            cuslist4.Add(cus2);

 

            cus3 = new Customer();

            cus3.Name = "John";

            cus3.Age = 27;

            cuslist4.Add(cus3);

 

            cus4 = new Customer();

            cus4.Name = "Kennedy";

            cus4.Age = 21;

            cuslist4.Add(cus4);

 

            cus5 = new Customer();

            cus5.Name = "Clinton";

            cus5.Age = 20;

            cuslist4.Add(cus5);

 

            Console.WriteLine("\nSort Based on Name with Range");

            CustomerNameSort esort4 = new CustomerNameSort();

            cuslist4.Sort(0, 3, esort4);

            foreach (Customer cus in cuslist4)

            {

                Console.WriteLine(cus.Name + " " + cus.Age);

            }

 

The output will be,

 

OUTPUT:

Sort Based on Name with Range

Bush 24

George 23

John 27

Kennedy 21

Clinton 20

 

Where the original unsorted list is,

George 23

Bush  24

John 20

Kennedy 21

Clinton 20

 

Since we have given start position as 0 and range as 3, the first 3 list elements are sorted using the comparer.

Reference

Implement Sort and Custom Enumerator in Generic List

Conclusion

Thus, we have understood all the sorting techniques on generic list in this article. Read my article sorting and custom enumeration on generic list which is linked in the reference section of this article.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
C# List
More about C# List

http://csharp.net-informations.com/collection/list.htm

Walsh
Tnx
very helpfull code
Very nice
Very helpful blog. For Further refrence
http://just-dotnet.blogspot.in/2012/06/c-generics-introduction.html
Very Helpful
Thank you. I'm a novice and it took me a little longer than 3 minutes, but I got this working and actually understand it.
BO
BO. A good writer never uses initials without explaining them the first time they are used (English 101). It may be obvious to you but may not be to your readers....
Excellent thanks
Excellent article it helps me alot. thanks again =)
dev
not very clear
Thanks you
Well explained. Took me only 3 mins to get my list sorted using your example.
Thanks
Very Helpful. Thanks!