Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in C#.
To run the program, save it as SortingByFunctions.cs and use the C# compiler:
In this C# version, we use the List<T> class’s Sort method, which accepts a Comparison<T> delegate. This allows us to provide custom sorting logic.
For sorting the Person objects, we use a lambda expression directly in the Sort method call. If the Person class is large, you might want to consider using a list of references (List<Person>) instead of values, which is already the case in C# (unlike structs in C#, classes are reference types by default).
Note that C# provides LINQ, which offers a more declarative way to sort collections. For example, you could use:
This approach can be more readable for simple sorting operations, but the Sort method with a custom comparer can be more efficient for complex or frequently used sorting logic.