Home > Articles > Programming > C#

  • Print
  • + Share This
Like this article? We recommend

Sorting a Generic Collection

It's pretty easy to sort a collection. Let's say that you want to sort the collection based on the names of its constituent elements. To do this, just implement the IComparable interface in the base class Person. Next, implement the CompareTo() method, using the default CompareTo() method of the data member on which you want to sort. Listing 10 points out the required changes.

Listing 10 Making the base class sortable.

public class Person : IComparable<Person>
{
  private String name;

  public Person(String name)
  {
   this.Name = name;
  }

  public string Name {
   get { return name; }
   protected set { name = value; }
  }

  public int CompareTo(Person other)
  {
   return name.CompareTo(other.name);
  }
}

Notice the addition of the CompareTo() method. When you want to sort the collection, the following code does the trick by simply invoking the Sort() method on the collection:

genericCollection.MyGenericCollection.Sort();

Listing 11 illustrates this code in action, where the unsorted list is displayed first, followed by the sorted list.

Listing 11 The list is unsorted and then sorted.

for (int i = 0; i < genericCollection.MyGenericCollection.Count; i++) {
  Console.WriteLine("Name is " + genericCollection.MyGenericCollection[i].Name);
}

Console.WriteLine();
genericCollection.MyGenericCollection.Sort();

for (int i = 0; i < genericCollection.MyGenericCollection.Count; i++) {
  Console.WriteLine("Sorted name is " + genericCollection.MyGenericCollection[i].Name);
}

Listing 12 shows the output from the code in Listing 11.

Listing 12 Sorted list output.

Collection capacity: 0
Person called: An Employee
Person called: A Contractor
Number of entries: 2
Number of entries: 2

Name is An Employee
Name is A Contractor

Sorted name is A Contractor
Sorted name is An Employee

Notice how the two entries in the collection in Listing 12 are reversed, based on the sorting algorithm. You can see that the order is alphabetical. That's all just fine, but what if we want to search a collection for a specific element? Again, this possibility isn't too difficult.

  • + Share This
  • 🔖 Save To Your Account