Hello, and welcome back! Our journey today takes us into the sorting universe in C#. We will learn about and utilize two built-in sorting functions: Array.Sort()
and List<T>.Sort()
. These tools in C# significantly simplify the task of sorting. Let's get started!
Sorting refers to arranging data in a specific order, which enhances the efficiency of search or merge operations on data. In real life, we sort books alphabetically or clothes by size. Similar concepts are applicable in programming, where sorting large lists of data for more effective analysis is a frequent practice.
C# offers built-in sorting methods: Array.Sort()
for arrays and List<T>.Sort()
for lists. Here's a demonstration of how we use these methods:
Sorting with Array.Sort()
makes sorting arrays of primitives a breeze. Let's see it in action!
Sorting Arrays of Primitives
Sorting Lists of Objects
As you can see, sorting in C# is as simple as that!
C# allows us to define custom sorting logic using lambda expressions. Let's sort a list of students by their grades, with alphabetical sorting applied in the event of ties in grades. First, let's define the Student
class:
Here's how we perform custom sorting using lambda expressions in C#:
In the example above, we create a List<Student>
and sort it using a custom comparison defined via a lambda expression. The lambda first compares Student
objects based on their grades in descending order and, in the event of a tie, compares their names in alphabetical order. The CompareTo
function returns an integer that indicates the relative order of the objects being compared: a negative integer if the first object precedes the second, zero if they are equal, and a positive integer if the first object follows the second. This method is commonly used in sorting operations to determine the order of elements.
To sort students by grades in ascending order but names in descending order in case of ties, you can adjust the lambda expression by flipping the order of the variables:
Here, the custom comparison sorts the grades in ascending order while sorting names in descending order when the grades are the same.
Well done! You've learned how sorting functions in C# work and have utilized C#'s built-in sorting functions.
In our future lessons, we'll delve deeper into sorting and tackle more intricate problems, such as finding the K-th largest number. So, stay tuned and get ready to sort your way to success! Happy coding!
