How do I sort custom object using ArrayList?
Category: System, viewed: 544 time(s).
In this example we sort a custom object using ArrayList.Sort() method. To enable the ArrayList.Sort() method sort the object have to implement the IComparable interface.
Our custom class is the Book class. This class implements the IComparable interface that will cause the ArrayList to sort the objects based on the book's ISBN property.
The Book class is a simple class with four properties. The ISBN, Title, Author and publishYear. The IComparable interface made the Book class to implement the CompareTo(object o) method.
For this example we just delegate the CompareTo() implementation to the string object CompareTo() method. This method should return three type of values, a positive, zero or negative value when the compared object value is greater, equals or smaller respectively.
using System;
namespace Kodecsharp.Example.System
{
class Book : IComparable
{
private string isbn;
private string title;
private string author;
private int publishYear;
public Book() {
}
public Book(string isbn) {
this.ISBN = isbn;
}
public string ISBN {
get {
return isbn;
}
set {
this.isbn = value;
}
}
//
// Other properties implemented here!
//
public int CompareTo(object o)
{
if (this.GetType() != o.GetType()) {
throw new ArgumentException("Object types is not equals.");
}
Book that = (Book) o;
return this.ISBN.CompareTo(that.ISBN);
}
public override string ToString() {
return "Book [" + this.ISBN + "]";
}
}
}