To use the List::Sort() function with user defined class objects,
Either we have to provide comparator function
or
Derive the corresponding class from IComparable interface and implement CompareTo function to define the behavior of the compare functions.
This is not only applicable for list but also any other generic containers or array to use the built-in sort option.
Either the comparator or the interface implementation must return an int
Less than zero - This instance precedes obj in the sort order.
Zero - This instance occurs in the same position in the sort order as obj.
Greater than zero - This instance follows obj in the sort order.
See the examples below
Using Comparator
class Book
{
public Book(string id, string name, string author)
{
ID = id;
Name = name;
Author = author;
}
public string ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
......
List listBook = new List();
listBook.Add(new Book( "103", "Code Complete", "Steve MC" ));
listBook.Add(new Book("101", "Effective C++", "Scott Meyers"));
listBook.Add(new Book("102", "CLR Via C#", "Jeff Prosise"));
listBook.Sort( CompareBook );
......
static int CompareBook(Book a, Book b)
{
return a.ID.CompareTo(b.ID);
}
Using delegates
Delegates are also similar to function pointers
listBook.Sort(
delegate(Book a, Book b)
{
return a.ID.CompareTo(b.ID);
});
Using IComparable
class Book : IComparable
{
public Book(string id, string name, string author)
{
ID = id;
Name = name;
Author = author;
}
public string ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public int CompareTo(object obj)
{
return ID.CompareTo(((Book)obj).ID);
}
}