Implement Sort and Custom Enumerator in Generic List
page 3 of 7
by Satheesh Babu
Feedback
Average Rating: 
Views (Total / Last 10 Days): 43803/ 122

Implementing Sort

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

Listing 3 - 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 work, Customer BO should inherit IComparable<Customer> and implement public int CompareTo(Customer  cus) method. So our final BO will look like:

Listing 4 - List.Sort () Implementation

class Customer: IComparable < Customer >
{
  //Members
  //1st Overload
  public int CompareTo(Customer cus)
  {
    return this.Name.CompareTo(cus.Name);
  }
}

Consider the following.

Listing 5 - 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 output of the above code will be,

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 6 - 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 two 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 to MSDN for more information.

Consider Customer BO in the section Things to Consider.

Here I am going to implement two 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 7 - 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.

Listing 8 - 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:

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 9 - - List.Sort (Generic IComparer) syntax

List.Sort (Generic IComparer) 

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

To implement the comparer implement IComparer<T> interface in a separate class use:

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

class CustomerNameSort : IComparer<Customer>
{
  public int Compare(Customer c1, Customer c2)
  {
    return c1.Name.CompareTo(c2.Name);
  }
}

Implement Compare() method as above to sort customers list based on name.

Usage

Listing 11 - 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:

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:

Listing 12 - 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 the number of elements to be sorted starting from the 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 the 3rd Overload - List.Sort (Generic IComparer) section.

 The comparer for our Customer BO will be:

Listing 13 - IComparer<Customer> implementation

class CustomerNameSort : IComparer<Customer>
{
  public int Compare(Customer c1, Customer c2)
  {
    return c1.Name.CompareTo(c2.Name);
  }
}

Usage

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

Listing 14 - 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:

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 the start position as 0 and range as 3, the first 3 list elements are sorted using the comparer.


View Entire Article

User Comments

Title: Comment box creation   
Name: Raghav
Date: 2011-11-01 1:43:04 PM
Comment:
I want to develop a comment box like face book in my website using ASP.net
Title: Mr   
Name: Banx
Date: 2010-10-06 6:59:59 PM
Comment:
With overload 2. Where does the comparecustomname method get the parameters from. its very confusing how it knows which parameters to use for the comparison.
Title: Implement Sort and Custom Enumerator in Generic List   
Name: Eric Ramírez
Date: 2010-04-09 11:58:27 PM
Comment:
The best article that i´ve found.

Thanks.
Title: Implement Sort and Custom Enumerator in Generic List   
Name: Saurabh
Date: 2008-12-25 12:16:29 PM
Comment:
Very nice explanation in a concise way...exactly to the point.
Title: Implement Sort and Custom Enumerator in Generic List   
Name: Michael
Date: 2008-04-12 10:30:13 PM
Comment:
Comprehensive and compact guide. And examples are actually working, in contrast to some MSDN articles
Title: Implement Sort and Custom Enumerator in Generic List   
Name: Wayde
Date: 2008-01-03 8:46:00 PM
Comment:
I have read a lot of stuff about custom enumeration and sorters and haven't understood any of it until I got to this article. Great Job! The article is concise, well organized, and the examples are fantastic.

Thank you.
Title: Implement Sort and Custom Enumerator in Generic List   
Name: Cheri
Date: 2008-01-03 3:02:25 AM
Comment:
cool article, learnt a lot of stuff from it






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-11-21 6:03:02 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search