Lesson 4
Sorting Techniques in C#: Harnessing Built-in Methods and Custom Logic
Lesson Introduction and Overview

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!

Understanding Sorting and Its Importance

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 of Primitive Types and Objects

Sorting with Array.Sort() makes sorting arrays of primitives a breeze. Let's see it in action!

Sorting Arrays of Primitives

C#
1int[] arr = {4, 1, 3, 2}; 2Array.Sort(arr); 3Console.WriteLine(string.Join(", ", arr)); // Output: 1, 2, 3, 4

Sorting Lists of Objects

C#
1List<string> inventory = new List<string> { "Bananas", "Pears", "Apples", "Dates" }; 2inventory.Sort(); 3foreach (string item in inventory) 4{ 5 Console.WriteLine(item); 6} 7 8// Output: 9// Apples 10// Bananas 11// Dates 12// Pears

As you can see, sorting in C# is as simple as that!

More Complex Sorting Problem

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:

C#
1class Student 2{ 3 public string Name { get; } 4 public int Grade { get; } 5 6 public Student(string name, int grade) 7 { 8 Name = name; 9 Grade = grade; 10 } 11 12 public override string ToString() 13 { 14 return $"{Name}:{Grade}"; 15 } 16}
Custom Sorting with Lambda Expressions

Here's how we perform custom sorting using lambda expressions in C#:

C#
1class Solution 2{ 3 static void Main(string[] args) 4 { 5 List<Student> students = new List<Student> 6 { 7 new Student("Alice", 85), 8 new Student("Bob", 90), 9 new Student("Charlie", 90) 10 }; 11 12 students.Sort((s1, s2) => 13 { 14 int gradeComparison = s2.Grade.CompareTo(s1.Grade); 15 return gradeComparison == 0 ? s1.Name.CompareTo(s2.Name) : gradeComparison; 16 }); 17 18 Console.WriteLine(string.Join(", ", students)); // Output: Bob:90, Charlie:90, Alice:85 19 } 20}

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.

Applying Reverse Order in Sorting

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:

C#
1students.Sort((s1, s2) => 2{ 3 int gradeComparison = s1.Grade.CompareTo(s2.Grade); 4 return gradeComparison == 0 ? s2.Name.CompareTo(s1.Name) : gradeComparison; 5}); 6 7// Output: Alice:85, Charlie:90, Bob:90

Here, the custom comparison sorts the grades in ascending order while sorting names in descending order when the grades are the same.

Lesson Summary and Next Steps

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.