c# - How to reverse a Dictionary items

Dictionary reverse
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can reverse the Dictionary element’s position. By default a Dictionary position its elements as they were added to the collection. But the .net developers can reverse the Dictionary elements position using the .net c# built-in method.

The Enumerable Reverse() method inverts the order of the elements in a sequence. The Enumerable Reverse() method returns a sequence whose elements correspond to those of the input sequence in reverse order.

The Enumerable ToDictionary() method creates a Dictionary<TKey,TValue> object from an IEnumerable<T>. The Enumerable Reverse() and the ToDictionary() methods both exist in System.Linq namespace.

Finally, we can reverse the Dictionary element's order using the Enumerable Reverse() method, and then we can convert the return sequence to a Dictionary using the Enumerable ToDictionary() method. As an example, after reversing Dictionary elements order it holds the last element first and the first element last, and so on.

<%@ Page Language="C#" AutoEventWireup="true"%>  
<!DOCTYPE html>      
<script runat="server">    
    protected void Button1_Click(object sender, System.EventArgs e)  
        //initialize a dictionary with keys and values.  
        Dictionary<int, string> birds = new Dictionary<int, string>() {  
            {1,"Antarctic Petrel"},  
            {2,"Northern Fulmar"},  
            {3,"Southern Giant Petrel"},  
            {4,"Antarctic Prion"},  
            {5,"Cape Petrel"}  

        Label1.Text = "dictionary elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        //reverse the elements of dictionary.
        birds = birds.Reverse().ToDictionary(x=>x.Key,x=>x.Value);
        Label1.Text += "<br /><br />dictionary after reverse elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary reverse</title>      
    <form id="form1" runat="server">      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary reverse
        <hr width="550" align="left" color="Gainsboro" />      
        <br /><br />    
            Text="dictionary reverse"      
More c# examples