c# - How to sort a list

Sort a List
The List class represents a strongly typed list of objects. This class provides methods to search, sort, and manipulate lists. The List class is the generic equivalent of the ArrayList class. The list is not guaranteed to be sorted. Elements of a list can be accessed using an integer index and the indexes are zero-based. The list accepts null as a valid value for reference types and allows duplicate elements.

The following .net c# tutorial code demonstrates how we can sort a list instance. In this tutorial, we will sort list elements alphabetically (ascending order) using a specified comparer. Here we will use the List class Sort() method to sort list items.

The List class Sort() method sorts the elements or a portion of the elements in the list using either the specified or default comparer implementation or a provided comparison delegate to compare list elements. The List class Sort(IComparer<T>) method overload sorts the elements in the entire list using the specified comparer.

The List Sort(System.Collections.Generic.IComparer<T>? comparer) method’s comparer parameter is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default. In this example code, we used the StringComparer.CurrentCulture for the comparer parameter value. The StringComparer.CurrentCulture gets a StringComparer object that performs a case-sensitive string comparison using the word comparison rules of the current culture.

The List Sort(comparer) method throws InvalidOperationException if the comparer is null, and the default comparer Default cannot find the implementation of the IComparable<T> generic interface or the IComparable interface for type T. It also throws ArgumentException if the implementation of comparer caused an error during the sort.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
        List<string> birds = new List<string> { "Maleo", "Wild Turkey", "Grey Partridge", "Congo Peafowl" };

        Label1.Text = "birds: ";
        foreach (string s in birds)
            Label1.Text += s + " | ";


        Label1.Text += "<br />birds Sorted : ";
        foreach (string s in birds)
            Label1.Text += s + " | ";

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>c# example - sorting a collection in alphabetical order</title>
    <form id="form1" runat="server">
        <h2 style="color:DarkBlue; font-style:italic;">
            c# example - sorting a collection in alphabetical order
        <hr width="550" align="left" color="LightBlue" />  

        <br /><br />
            Text="Sort Collection in alphabetical order"