c# - How to sort list items in ascending order

Sort list items in ascending order
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 list items in ascending order. Here we will use the Enumerable class OrderBy() method to sort list items. And the Enumerable class ToList() method to convert the sorted sequence to a list object.

The Enumerable class OrderBy() method sorts the elements of a sequence in ascending order. This method returns an ascending sorted sequence. Then we will call the Enumerable ToList() method to convert the returned sequence to a list.

The Enumerable ToList() method creates a List from a sequence. This method throws ArgumentNullException If the source sequence is null.

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

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
        List<string> colors = new List<string> { "red", "indianred", "crimson", "pink" };

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

        List<string> sortedcolors = colors.OrderBy(x => x).ToList();

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>c# example - generic List<> OrderBy Alphabetical Order</title>
    <form id="form1" runat="server">
        <h2 style="color:DarkBlue; font-style:italic;">
            c# example - generic List<> 
            <br />OrderBy Alphabetical Order
        <hr width="550" align="left" color="LightBlue" />  

        <br /><br />
            Text="Generic List<> OrderBy"