C# Dictionary根据Key排序

来源:互联网 发布:影楼制作软件apk 编辑:程序博客网 时间:2024/06/03 05:07
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication1  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.   
  13.             Dictionary<intstring> test = new Dictionary<intstring> { };  
  14.             test.Add(0,"000");  
  15.             test.Add(4, "444");  
  16.             test.Add(2, "222");  
  17.             test.Add(6, "666");  
  18.   
  19.             Dictionary<intstring> dic1Asc = test.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);  
  20.               
  21.               
  22.             Console.WriteLine("小到大排序");  
  23.             foreach(KeyValuePair<int,string> k in dic1Asc){  
  24.                 Console.WriteLine("key:" +k.Key +" value:" + k.Value);  
  25.             }  
  26.   
  27.             Console.WriteLine("大到小排序");  
  28.             Dictionary<intstring> dic1desc = test.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);  
  29.   
  30.             foreach (KeyValuePair<intstring> k in dic1desc)  
  31.             {  
  32.                 Console.WriteLine("key:" + k.Key + " value:" + k.Value);  
  33.             }  
  34.   
  35.   
  36.             while (true) ;  
  37.   
  38.         }  
  39.     }  
  40. }