How to Sort Dictionary Object based on Value

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class Default2 : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.         Dictionary<stringstring> objCountries = new Dictionary<stringstring>();  
  13.           
  14.         //Adding countries to dictionary in random order  
  15.         objCountries.Add("India""India");  
  16.         objCountries.Add("America""America");  
  17.         objCountries.Add("Canada""Canada");  
  18.         objCountries.Add("Britain""Britain");  
  19.         objCountries.Add("New Zealand""New Zealand");  
  20.         objCountries.Add("Nepal""Nepal");  
  21.         objCountries.Add("Myanmar""Myanmar");  
  22.         objCountries.Add("China""China");  
  23.         objCountries.Add("Singapore""Singapore");  
  24.   
  25.   
  26.         //Sorting the countries in the dictionary object based on value  
  27.         List<KeyValuePair<stringstring>> mySortedList = objCountries.ToList();  
  28.   
  29.         mySortedList.Sort(  
  30.             delegate(KeyValuePair<stringstring> firstPair,  
  31.             KeyValuePair<stringstring> nextPair)  
  32.             {  
  33.                 return firstPair.Value.CompareTo(nextPair.Value);  
  34.             }  
  35.         );  
  36.     }  
  37. }