Aug 12, 2008

How to sort generic collection

Hi all,

We will now sort generic collection. For this we need to create one comparere class which inherits IComparer<T> and implement Compare method, where T is your class object. Compare method is responsible to compare tow object and based on the result sorting will be done.

public class TestSortComparere : IComparer<TestSort>
public TestSortComparere() { }

#region IComparer<TestSort> Members

public int Compare(TestSort x, TestSort y)
return string.Compare(x.a, y.a);


Now lets call Sort method.

List<TestSort> MyObjList = new List<TestSort>();
MyObjList.Add(new TestSort("Imran"));
MyObjList.Add(new TestSort("Dipak"));
MyObjList.Add(new TestSort("Sachin"));
MyObjList.Add(new TestSort("Darshan"));
MyObjList.Add(new TestSort("Gaurav"));

MyObjList.Sort(new TestSortComparere());

You can see the sorted order when you iterate MyObjList

foreach (TestSort testSort in MyObjList)
Console.Write(testSort.strTest + Environment.NewLine);

We can change the sort line using Anonymous delegate. Lets see how, its only in single line!!!!.

MyObjList.Sort(delegate(TestSort x, TestSort y) { return string.Compare(x.strTest, y.strTest); });

No comments: