Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
Print
(untagged)

How to Sort an Object List in C#

0.00/5 (No votes)
18 Apr 2014 1  
How to sort an object list in C#

Introduction

This tip shows how to sort an object list in C#.

Take this template class as an example.

C#
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

C#
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

C#
list.Sort(delegate(Member x, Member y)
{
    return x.Total.CompareTo(y.Total);
});

Sort by Single Element "Total" in Descending Order

C#
lst.Sort(delegate(Member  x, Member  y)
{
    return y.Total.CompareTo(x.Total);
});

Sort by Multiple Elements

C#
list.Sort(delegate(Member  x, Member y)
{
    // Sort by total in descending order
    int a = y.Total.CompareTo(x.Total);

    // Both Member has the same total.
    // Sort by name in ascending order
    a = x.Name.CompareTo(y.Name);

    return a;
});

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here