Click here to Skip to main content
12,395,001 members (59,352 online)
Click here to Skip to main content
Add your own
alternative version

Stats

15.8K views
5 bookmarked
Posted

How to Sort an Object List in C#

, 18 Apr 2014 CPOL
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.

You may also be interested in...

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.

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