Click here to Skip to main content
15,394,785 members
Articles / Programming Languages / C# 3.5
Tip/Trick
Posted 18 Apr 2014

Stats

54.9K views
6 bookmarked

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
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)

Share

About the Author

Member 4742039
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
Member_groo_22-Apr-14 2:54 
GeneralMy vote of 2 Pin
sargsyangugo21-Apr-14 11:20
Membersargsyangugo21-Apr-14 11:20 
QuestionThat last snippet won't work Pin
_groo_18-Apr-14 5:38
Member_groo_18-Apr-14 5:38 
AnswerRe: That last snippet won't work Pin
adriancs18-Apr-14 15:29
professionaladriancs18-Apr-14 15:29 

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.