Sort Dictionary in C# Using OrderBy

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace TestCalculator  
  5. {  
  6.       class Program  
  7.       {  
  8.             static void Main(string[] args)  
  9.             {  
  10.                   Console.WriteLine("/* life runs on code */");  
  11.                   //Dictionary.  
  12.                   var dictionary = new Dictionary<stringint>(5);  
  13.                   dictionary.Add("Anil", 1);  
  14.                   dictionary.Add("Amol", 0);  
  15.                   dictionary.Add("Pravin Singh", 5);  
  16.                   dictionary.Add("Jeet", 3);  
  17.                   dictionary.Add("Sadhana", 2);  
  18.                   //Using Order by values.  
  19.                   //LINQ to specify sorting by value.  
  20.                   var sorts = from pair in dictionary  
  21.                   orderby pair.Value ascending  
  22.                   select pair;  
  23.                   // Display results.  

  24.                   foreach (var sort in sorts)  
  25.                   {  
  26.                         Console.WriteLine("{0}: {1}", sort.Key, sort.Value);  
  27.                   }  
  28.             }  
  29.       }  
  30. }