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:
Reference:
Comparison(T) Generic Delegate
No comments:
Post a Comment