Click here to Skip to main content
Click here to Skip to main content
Go to top

How to Sort an Object List in C#

, 18 Apr 2014
Rate this:
Please Sign up or sign in to vote.
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.

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)
{
    // 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 Pinmember_groo_22-Apr-14 2:54 
GeneralMy vote of 2 Pinmembersargsyangugo21-Apr-14 11:20 
QuestionThat last snippet won't work Pinmember_groo_18-Apr-14 5:38 
AnswerRe: That last snippet won't work Pinpremiumadriancs18-Apr-14 15:29 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 18 Apr 2014
Article Copyright 2014 by Member 4742039
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid