Sorting in C#

Our example demonstrates sorting in C#. We’ll look at sorting for built-in types first.

using System;
using System.Collections.Generic;

class Sorting
{
    static void Main()
    {
        // Sorting functions work for any IComparable<T> type.
        // This includes most built-in types like string, int, etc.
        
        var strs = new List<string> { "c", "a", "b" };
        strs.Sort();
        Console.WriteLine("Strings: " + string.Join(", ", strs));

        // An example of sorting ints.
        var ints = new List<int> { 7, 2, 4 };
        ints.Sort();
        Console.WriteLine("Ints:    " + string.Join(", ", ints));

        // We can also check if a list is already in sorted order.
        bool s = IsSorted(ints);
        Console.WriteLine("Sorted:  " + s);
    }

    // Helper method to check if a list is sorted
    static bool IsSorted<T>(List<T> list) where T : IComparable<T>
    {
        for (int i = 1; i < list.Count; i++)
        {
            if (list[i-1].CompareTo(list[i]) > 0)
            {
                return false;
            }
        }
        return true;
    }
}

In C#, we use the List<T> class from the System.Collections.Generic namespace to work with lists of items. The Sort() method is available on List<T> for any type T that implements IComparable<T>, which includes most built-in types like string and int.

We create and sort lists of strings and integers. The Sort() method modifies the list in place.

To check if a list is sorted, we implement a custom IsSorted<T> method. C# doesn’t have a built-in method for this, unlike the slices.IsSorted() function in Go.

When you run this program, you should see:

Strings: a, b, c
Ints:    2, 4, 7
Sorted:  True

This demonstrates basic sorting functionality in C#. For more complex sorting scenarios, C# offers additional methods like OrderBy() and ThenBy() in LINQ, and custom sorting can be implemented using the IComparer<T> interface.