You can use System.IComparable interface to sort a genric list
class Employee : IComparable {
private string _firstname;
private decimal _salary;
public Employee(string _firstname, decimal _salary) {
this._firstname = _firstname;
this._salary = _salary;
}
public string FirstName {
get {
return _firstname;
}
set {
_firstname = value;
}
}
public decimal Salary {
get {
return _salary;
}
set {
_salary = value;
}
}
// Compares the current instance with another object of the same type. (sorts in ascending order)
public int CompareTo(object obj) {
Employee Employee = (Employee)obj;
return
this.FirstName.CompareTo(Employee);
}
}
Sorting using IComparable interface:
List<Employee> emp = new List<Employee>();
emp.Add(new Employee("Bill",80000.1m));
emp.Add(new Employee("Jeff", 90000.99m));
emp.Add(new Employee("Kelly", 100000));
// sort in ascending order
emp.Sort(delegate(Employee emp0, Employee emp1) {
return
emp0.FirstName.CompareTo(emp1.FirstName);
});
// sort in descending order
emp.Sort(delegate(Employee emp0, Employee emp1) {
return
emp1.FirstName.CompareTo(emp0.FirstName);
});