Click here to Skip to main content
16,013,918 members
Articles / Programming Languages / C# 3.5
Tip/Trick

How to Sort an Object List in C#

Rate me:
Please Sign up or sign in to vote.
3.17/5 (5 votes)
18 Apr 2014CPOL 57.8K   6   4
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) mrcc
India India
I am honest man,honest husband,father of twin daughters and asp.net developer.I like to code in c#,node.js.I have passed MCP and MCTS exam.I have total 7 years experience web development experience.

Comments and Discussions

 
GeneralMy vote of 2 Pin
_groo_22-Apr-14 2:54
_groo_22-Apr-14 2:54 
GeneralMy vote of 2 Pin
sargsyangugo21-Apr-14 11:20
sargsyangugo21-Apr-14 11:20 
QuestionThat last snippet won't work Pin
_groo_18-Apr-14 5:38
_groo_18-Apr-14 5:38 
AnswerRe: That last snippet won't work Pin
adriancs18-Apr-14 15:29
mvaadriancs18-Apr-14 15:29 
Well, I doubt that if he even understand the code or not. He is just re-posting (copying) my initial tips of
How to Sort a List (C#)[^] without any new concept or new syntax changes by his honest behavior as he mentioned in his biography (honest man and husband). With 7 years of development experiences, he can't produce his own code and even copied the wrong version of codes with bugs.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.