Click here to Skip to main content
15,878,814 members
Articles / Programming Languages / C#
Tip/Trick

How to Sort a List (C#)

Rate me:
Please Sign up or sign in to vote.
4.54/5 (15 votes)
18 Apr 2014CPOL2 min read 179.7K   6   16
Tips on sorting a list of objects.

 

Take this class as example.

C#
public class Player
{
    public string Name { get; set; }
    public int Total { get; set; }

    public Player(string name, int total)
    {
        Name = name;
        Total = total;
    }
}

Creating the list.

C#
List<Player> lst = new List<player>();
lst.Add(new Player("John", 100));
lst.Add(new Player("Smith", 120));
lst.Add(new Player("Cait", 97));
lst.Add(new Player("Irene", 100));
lst.Add(new Player("Ben", 100)); 
lst.Add(new Player("Deniel", 88));

Sort By Using List<t>.Sort() Method

Sort by single element "Total" in ascending order:

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

Sort by single element "Total" in descending order:

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

Sort by multiple elements:

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

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

    return a;
});

Sort By Using Linq

Sorting by using Linq requires less syntax.

C#
var result1 = lst.OrderBy(a => a.Total);

var result3 = lst.OrderBy(a => a.Total).ThenBy(a => a.Name);

var result2 = lst.OrderByDescending(a => a.Total).ThenByDescending(a => a.Name);

Comparing List.Sort and LINQ Methods for Sorting in C#

When it comes to sorting lists in C#, developers often find themselves choosing between List.Sort and LINQ methods like OrderBy(). Both approaches come with their own sets of advantages and disadvantages. In this article, we'll dive deep into each approach to help you make an informed decision.

LINQ (Language Integrated Query)

Pros

  • Readability: LINQ queries are generally more readable and self-explanatory, making the code easier to understand.

  • Composability: LINQ allows you to easily chain multiple operations together, facilitating complex queries.

  • Type Safety: Benefit from compile-time type checking, reducing the likelihood of runtime errors.

  • Flexibility: Use LINQ for various data sources, not just in-memory collections but also databases, XML, and more.

  • Deferred Execution: Queries aren't executed until you actually need the data, offering performance improvements in certain scenarios.

Cons

  • Performance: In performance-critical applications, LINQ can be slower than optimized loops and delegates.

  • Debugging: Tracing through LINQ queries may not be as straightforward as conventional loops and delegate calls.

Additional Considerations

  • Memory Overhead: Queries involving ordering or filtering create new sequences, consuming additional memory.

  • CPU Overhead: While generally not significant for most applications, LINQ's abstraction layer can introduce some CPU overhead.

Delegates with List.Sort

Pros

  • Performance: Being function pointers under the hood, delegates are generally faster for simple sorting operations.

  • Flexibility: Beyond sorting and filtering, delegates can also be used for event handling and callbacks.

  • Explicit Control: You have more direct control over the comparison logic and the flow of execution.

Cons

  • Readability: Code using delegates may be harder to maintain and understand.

  • Verbosity: For simple operations, using delegates can make the code more verbose compared to LINQ.

Additional Considerations

  • In-Place Sorting: List.Sort modifies the original list, consuming no extra memory for a new list.

Conclusion

Choosing between List.Sort and LINQ methods boils down to your specific project needs.

  • For Immutability: If preserving the original list is crucial, LINQ is the way to go as it produces a new sorted sequence.

  • For Resource Efficiency: If you want to minimize memory and CPU usage, List.Sort would be more suitable since it sorts the list in-place.

Ultimately, neither method is universally "better"; both have their place depending on the context of your application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Other Other
Programming is an art.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 347330518-Jun-21 15:34
Member 347330518-Jun-21 15:34 
QuestionDisplaying Pin
Member 1522078728-May-21 5:41
Member 1522078728-May-21 5:41 
QuestionThanks for sharing Easy and quick solution for any type collection sorting Pin
Mr.Rajendra Taradale4-Dec-17 19:48
Mr.Rajendra Taradale4-Dec-17 19:48 
GeneralMy vote of 4 Pin
Peter Huber SG13-Jul-15 23:00
mvaPeter Huber SG13-Jul-15 23:00 
GeneralMy vote of 2 Pin
LostTheMarbles22-Apr-14 4:24
professionalLostTheMarbles22-Apr-14 4:24 
QuestionSome more ways to sort . Pin
George Swan18-Apr-14 21:34
mveGeorge Swan18-Apr-14 21:34 
GeneralMy vote of 2 Pin
Emre Ataseven18-Apr-14 2:17
professionalEmre Ataseven18-Apr-14 2:17 
GeneralRe: My vote of 2 Pin
SRKarn18-Apr-14 5:35
SRKarn18-Apr-14 5:35 
GeneralMy vote of 1 Pin
giganoide17-Apr-14 23:10
giganoide17-Apr-14 23:10 
GeneralRe: My vote of 1 Pin
adriancs18-Apr-14 0:10
mvaadriancs18-Apr-14 0:10 
GeneralRe: My vote of 1 Pin
Daniele Rota Nodari9-May-21 0:10
Daniele Rota Nodari9-May-21 0:10 
GeneralMy vote of 1 Pin
mariuszkiler17-Apr-14 23:02
mariuszkiler17-Apr-14 23:02 
GeneralRe: My vote of 1 Pin
adriancs17-Apr-14 23:11
mvaadriancs17-Apr-14 23:11 
GeneralRe: My vote of 1 Pin
mariuszkiler17-Apr-14 23:15
mariuszkiler17-Apr-14 23:15 
GeneralRe: My vote of 1 Pin
adriancs18-Apr-14 0:10
mvaadriancs18-Apr-14 0:10 
GeneralRe: My vote of 1 Pin
HaBiX19-Apr-14 20:11
HaBiX19-Apr-14 20:11 

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.