Sorting custom objects implementing IComparable

Today a friend of mine asked me how to sort a list collection of custom object. The answer is very simple. All you need to do is to implement IComparable interface and it's method CompareTo. Lets see a little code:

In our scenario we have a class that represents some doc. It has only 2 property members. We gonna use docID for sorting criteria ;).



public int docID { get; set; }
public string SomeImportantDocText { get; set; }



The class has one method CompareTo (implemented from IComparable)



public int CompareTo(object obj)
{
ImportantDoc imd = (ImportantDoc)obj;

return docID.CompareTo(imd.docID);

}



Here comes the whole class declaration:



public class ImportantDoc : IComparable
{

public int docID { get; set; }
public string SomeImportantDocText { get; set; }

public int CompareTo(object obj)
{
ImportantDoc imd = (ImportantDoc)obj;

return docID.CompareTo(imd.docID);

}
}


Now if we have a unsorted collection of List



List docs = new List();

///adding some unsorted docs





Calling


docs.Sort()


will sort our collection.

If you want some different business logic, or sorting on two fields and so on... you need to create your own Comparer by declaring class and implementing IComparer interface.

0 коментара:

Публикуване на коментар

top