标签:
SortedDictionary<TKey,TValue>能对字典排序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SortDictionary { class Program { static void Main(string[] args) { TestDictionarySort(); TestDictionarySort2(); Console.Read(); } private static void TestDictionarySort() { SortedDictionary<string, string> sd = new SortedDictionary<string, string>(); sd.Add("321", "fdsgsags"); sd.Add("acb", "test test"); sd.Add("1123", "lslgsgl"); sd.Add("2bcd13", "value"); foreach (KeyValuePair<string, string> item in sd) { Console.Write("键名:" + item.Key + " 键值:" + item.Value+"\r\n"); } } private static void TestDictionarySort2() { SortedDictionary<string, string> sd = new SortedDictionary<string, string>(); sd.Add("321", "fdsgsags"); sd.Add("acb", "test test"); sd.Add("1123", "lslgsgl"); sd.Add("2bcd13", "value"); Console.Write("\r\n正序排序数据:\r\n"); foreach (KeyValuePair<string, string> item in sd) { Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n"); } //重新封装到Dictionary里(PS:因为排序后我们将不在使用排序了,所以就使用Dictionary) Dictionary<string, string> dc = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> item in sd.Reverse()) { dc.Add(item.Key, item.Value); } sd = null; //再看其输出结果: Console.Write("\r\n反序排序数据:\r\n"); foreach (KeyValuePair<string, string> item in dc) { Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n"); } } } }
结果:
SortedDictionary<TKey,TValue>正序与反序排序
标签:
原文地址:http://www.cnblogs.com/shy1766IT/p/5046389.html