Introduction
This tip shows how to sort an object list in C#.
Take this template class as an example.
public class Member
{
public string Name { get; set; }
public int Total { get; set; }
public Member(string name, int total)
{
Name = name;
Total = total;
}
}
Create the List
List<Member> list = new List<member>();
list.Add(new Member("Kishor", 600));
list.Add(new Member("Rahul", 7120));
list.Add(new Member("Ratish", 997));
list.Add(new Member("Supriya", 1100));
list.Add(new Member("Aditi", 1100));</member>
Sort by Single Element in Ascending Order
list.Sort(delegate(Member x, Member y)
{
return x.Total.CompareTo(y.Total);
});
Sort by Single Element "Total" in Descending Order
lst.Sort(delegate(Member x, Member y)
{
return y.Total.CompareTo(x.Total);
});
Sort by Multiple Elements
list.Sort(delegate(Member x, Member y)
{
int a = y.Total.CompareTo(x.Total);
a = x.Name.CompareTo(y.Name);
return a;
});