c# - How to sort a Dictionary by DateTime value

Sort a Dictionary by DateTime value
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can sort Dictionary elements by DateTime value. How can we sort Dictionary items in ascending and descending order while their values are DateTime data type?

In this .net c# tutorial code we initialize a Dictionary instance whose value data type is DateTime and the key data type is Int. We have to sort the Dictionary elements in ascending and descending order by their DateTime data type values. By default, Dictionary object holds their elements as they are added or put in initializing time.

The Enumerable OrderBy() method sorts the elements of a sequence in ascending order and the OrderByDescending() method sorts the elements of a sequence in descending order. So we can sort the Dictionary elements in ascending and descending order using this OrderBy() and OrderByDescending() methods. The Enumerable OrderBy() and OrderByDescending() methods are located under the System.Linq namespace.

The Enumerable OrderBy() method returns an IOrderedEnumerable<TElement> whose elements are sorted according to a key and the OrderByDescending() method returns an IOrderedEnumerable<TElement> whose elements are sorted in descending order according to a key. The Enumerable ToDictionary() method creates a Dictionary<TKey,Tvalue> from an IEnumerable<T>.
dictionary-sort-by-datetime.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with date time values.
        Dictionary<int, DateTime> dc = new Dictionary<int, DateTime>() {
            {1,DateTime.Today},
            {2,DateTime.Today.AddDays(3)},
            {3,DateTime.Today.AddDays(1)},
            {4,DateTime.Today.AddDays(10)},
            {5,DateTime.Today.AddDays(5)},
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }

        //ascending sorted dictionary by date time value.
        dc = dc.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />ascending sorted dictionary by date time value..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }

        //descending sorted dictionary by date time values.
        dc = dc.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />descending sorted dictionary by date time values..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary sort by datetime</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary sort by datetime
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary sort by datetime"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples