How to sort items in a list in C#
Submitted by softking on Mon, 06/16/2008 - 18:34
Sorting lists in C# with support of the interface IComparable
for example we have objects from the class TestItem in a list
public class TestItem
{
private int sortByMe;
}Here is the list definition
private List<TestItem> testItems = new List<TestItem>(); In order to sort it using the internal members of the class TestItem (i.e. sortByMe field) , the class must inherit from IComparable interface and implement its single method
public int CompareTo(object other)
{
//first check that we compare againt the same type
if(!( other is TestItem)){
return 0;
}
TestItem otherItem = (TestItem)other;
if (otherItem.sortByMe> this.sortByMe)
return -1;
if (otherItem.sortByMe< this.sortByMe)
return 1;
return 0; // they are equal
}Now to do the actual sorting we use this code
testItems.Sort();