SortedDictionary分类字典和Dictionary字典的区别
static void Main(string[] args) { TestSortedDictionary(); TestSortedDictionary2(); TestDictionary(); Console.Read(); }
默认:测试SortedDictionary分类字典
/// <summary> /// 测试SortedDictionary分类字典 /// </summary> private static void TestSortedDictionary() { Console.WriteLine("\n\n\n-----测试SortedDictionary分类字典-----"); SortedDictionary<string, string> sd = new SortedDictionary<string, string>(); sd.Add("a", "aaa"); sd.Add("c", "bbb"); sd.Add("b", "ccc"); sd.Add("d", "ddd"); foreach (KeyValuePair<string, string> item in sd) { Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n"); } }
默认:测试Dictionary字典
/// <summary> /// 测试Dictionary字典 /// </summary> private static void TestDictionary() { Console.WriteLine("\n\n\n-----测试Dictionary字典-----"); Dictionary<string, string> testdict = new Dictionary<string, string>(); testdict.Add("a", "a"); testdict.Add("c", "c"); testdict.Add("b", "b"); testdict.Add("d", "d"); testdict.Remove("a"); testdict.Add("a", "a"); foreach (KeyValuePair<string, string> item in testdict) { Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n"); } }
测试SortedDictionary分类字典的正序和反序
/// <summary> /// 测试SortedDictionary分类字典的正序和反序 /// </summary> private static void TestSortedDictionary2() { Console.WriteLine("\n\n\n-----测试SortedDictionary分类字典的正序和反序-----"); SortedDictionary<string, string> sd = new SortedDictionary<string, string>(); sd.Add("a", "aaa"); sd.Add("c", "bbb"); sd.Add("b", "ccc"); sd.Add("d", "ddd"); 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的特性无论插入字典的数据是乱序还是有序,他都会根据ASCII码从小到大排序
Dictionary则是根据插入顺序进行的排序
qq:527592435