Friday, May 2, 2008

Sorting with help of delegate Comparison.

    When we use Generic class List(T), we can easy to sort it with help of method Sort and delegate Comparison.

Sample.

Definition of class Data:

internal class Data
{
internal int id;
internal string name;
internal Data(int id, string name)
{
this.id = id;
this.name = name;
}
}



Initialization of List<Data>:



List<Data> dataList = new List<Data>();
dataList.Add(new Data(4, "London"));
dataList.Add(new Data(2, "Rome"));
dataList.Add(new Data(3, "New York"));
dataList.Add(new Data(5, "Paris"));
dataList.Add(new Data(1, "Jerusalem"));

DataServices.PrintList("by original order:", dataList);



Sorting dataList by field id:



dataList.Sort(delegate(Data data1, Data data2) { return data1.id - data2.id; });
DataServices.PrintList("by id:", dataList);



Sorting dataList by field name:



dataList.Sort(delegate(Data data1, Data data2) { return String.Compare(data1.name, data2.name); });
DataServices.PrintList("by name:", dataList);



Console output:



consoleComparison



Reference:



List(T).Sort Method



Comparison(T) Generic Delegate



Using IComparable and IComparer to compare objects

No comments: