How to Sort a List (C#)

Take this class as example.

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.

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:

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

Sort by single element “Total” in descending order:

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

Sort by multiple elements:

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.

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 SortingList.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.