c# - How to sort a Dictionary by key and value

Dictionary sort by key and value
dictionary-sort-by-key-and-value.aspx

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

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Dictionary<string, int> colors = new Dictionary<string, int>();
        colors.Add("red",5);
        colors.Add("green",3);
        colors.Add("blue",1);
        colors.Add("magenta",2);
        colors.Add("maroon",4);

        Label1.Text = "Colors:.........<br />";
        foreach (KeyValuePair<string, int> pair in colors)
        {
            Label1.Text += pair.Key + " | " + pair.Value + "<br />";
        }

        Label1.Text += "<br />Sorted Colors By Value:.........<br />";
        var sortedcolors = from pair in colors
                    orderby pair.Value ascending
                    select pair;
        foreach (KeyValuePair<string,int> pair in sortedcolors )
        {
            Label1.Text += pair.Key + " | " + pair.Value + "<br />";
        }

        Label1.Text += "<br />Sorted Colors By Key:.........<br />";
        var sortedcolorsbykey = from pair in colors
                           orderby pair.Key ascending
                           select pair;
        foreach (KeyValuePair<string, int> pair in sortedcolorsbykey)
        {
            Label1.Text += pair.Key + " | " + pair.Value + "<br />";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>c# example - dictionary sort by key and value</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            c# example - dictionary sort by key and value
        </h2>
        <hr width="550" align="left" color="LightBlue" />  

        <asp:Label 
            ID="Label1" 
            runat="server"
            Font-Size="Large"
            >
        </asp:Label>
        <br />
        <asp:Button 
            ID="Button1" 
            runat="server" 
            Text="sort dictionary by key and value"
            OnClick="Button1_Click"
            Height="40"
            Font-Bold="true"
            />
    </div>
    </form>
</body>
</html>
More c# examples