Sorting a list of objects


A programmer often comes across a situation in which he has to sort a list of numbers or a series of objects. Sorting primitive types is a very easy job in .NET because the Array class provides a static method named Array.Sort which sorts an array in ascending order. The following example demonstrates how to sort an array of integer values:

using System;

using System.Collections.Generic;

using System.Text;

namespace SortPrimitive

{

class Program

{

static void Main(string[] args)

{

int[] intList=new int[3];

intList[0] = 5;

intList[1] = 3;

intList[2] = 1;

Array.Sort(intList);

foreach (int a in intList)

Console.WriteLine(a);

Console.ReadKey();

}

}

}

You can also create an instance of generic LIST<T> class to sort it’s members out, only if T is a primitive type:

namespace SortPrimitive

{

class Program

{

static void Main(string[] args)

{

List<int> intList = new List<int>();

intList.Add(5);

intList.Add(3);

intList.Add(1);

intList.Sort();

foreach (int a in intList)

Console.WriteLine(a);

Console.ReadKey();

}

}

}

But what about a list of objects? For example suppose that there is list of Person class. The definition of this class is as follows:

public class Person

{

int age = 0;

public int Age

{

get { return age; }

set { age = value; }

}

int workexp = 0;

public int Workexp

{

get { return workexp; }

set { workexp = value; }

}

string fullname = “”;

public string Fullname

{

get { return fullname; }

set { fullname = value; }

}

}

If you try to sort a list of Person class in this way, you will get an exception. The reason is pretty clear: We can sort objects based on various properties, therefore, we must clarify how two objects must be compared.

In order to get two objects compared, those objects must implement IComparable or IComparable<T> interface. This interface has a method named CompareTo which returns an integer value. This value is interpreted as bellow:

Value

Meaning

Less than zero

This instance is less than obj.

Zero

This instance is equal to obj.

Greater than zero

This instance is greater than obj.

For example in order to compare two Persons, we must write a code like this:

public int CompareTo<Person>(Person ComparedTo)

{

if (this.Age == ComparedTo.Age)

return 0;

else

return this.Age > ComparedTo.age ? 1 : -1;

}

Now if we create an instance of LIST class and add some Person objects into it, simply by calling the Sort method, all objects are sorted based on their Age property:

List<Person> PersonList = new List<Person>();

Person person;

person = new Person();

person.Age = 35;

PersonList.Add(person);

person = new Person();

person.Age = 25;

PersonList.Add(person);

person = new Person();

person.Age = 15;

PersonList.Add(person);

PersonList.Sort();

foreach (Person a in PersonList)

Console.WriteLine(a.Age);

Console.ReadKey();

When teaching this subject to my students I always ask them to write this program as an exercise:

Define a class named book with these properties:

1-Title

2-Publishing year

3-Price

Write a code to get unknown numbers of Book objects from standard console, sort them and write the sorted list back to the screen.

You can download the code of this example from HERE, but I suggest that you write it by yourself fist.

In other posts I will write more about sorting.

p.s. A PDF version of this post is available here.

Aref Karimi

June 2008


Advertisements

2 thoughts on “Sorting a list of objects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s