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

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

Sorting Lists of Objects

List<string> inventory = new List<string> { "Bananas", "Pears", "Apples", "Dates" };
inventory.Sort();
foreach (string item in inventory)
{
    Console.WriteLine(item);
}

// Output:
// Apples
// Bananas
// Dates
// 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:

class Student
{
    public string Name { get; }
    public int Grade { get; }

    public Student(string name, int grade)
    {
        Name = name;
        Grade = grade;
    }

    public override string ToString()
    {
        return $"{Name}:{Grade}";
    }
}
Custom Sorting with Lambda Expressions

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

class Solution
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>
        {
            new Student("Alice", 85),
            new Student("Bob", 90),
            new Student("Charlie", 90)
        };

        students.Sort((s1, s2) => 
        {
            int gradeComparison = s2.Grade.CompareTo(s1.Grade);
            return gradeComparison == 0 ? s1.Name.CompareTo(s2.Name) : gradeComparison;
        });

        Console.WriteLine(string.Join(", ", students)); // Output: Bob:90, Charlie:90, Alice:85
    }
}

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal