使用过Dictionary的人都知道,当每一个Add里面的值都不会改变其顺序,所以需要需要对其排序的时候就用到SortedDictionary,但SortedDictionary并不是那么理想,其默认的方式只支持正序排序,想要反序排序时必须得靠自己重新编写代码,下面来看一个简单的例子:
测试环境为Web,如在WinForm下,调试则只需改一下输出语句即可。
如以下代码在调试时不能使用则需要引用:
using System.Linq;
using System.Collections.Generic;
1 private void TestDictionarySort()2 {
3 SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
4 sd.Add("321", "fdsgsags");
5 sd.Add("acb", "test test");
6 sd.Add("1123", "lslgsgl");
7 sd.Add("2bcd13", "value");
8 sd.Reverse();//内置的反序无效
9
10 foreach (KeyValuePair<string, string> item in sd)
11 {
12 Response.Write("键名:" + item.Key + " 键值:" + item.Value);
13 }
14
15 }
上面代码输出效果:
键名:1123 键值:lslgsgl
键名:2bcd13 键值:value
键名:321 键值:fdsgsags
键名:acb 键值:test test
其结果证明了使用“sd.Reverse();”无效,好了,现在我们就是要使用另类的方法来使其生效而达到反序排序的效果,请看下面的代码:
private 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");
Response.Write("<br />正序排序数据:<br />");
foreach (KeyValuePair<string, string> item in sd)
{
Response.Write("键名:" + item.Key + " 键值:" + item.Value + "<br />");
}
//重新封装到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;
//再看其输出结果:
Response.Write("<br />反序排序数据:<br />");
foreach (KeyValuePair<string, string> item in dc)
{
Response.Write("键名:" + item.Key + " 键值:" + item.Value + "<br />");
}
}
上面代码输出效果:
正序排序数据:
键名:1123 键值:lslgsgl
键名:2bcd13 键值:value
键名:321 键值:fdsgsags
键名:acb 键值:test test
反序排序数据:
键名:acb 键值:test test
键名:321 键值:fdsgsags
键名:2bcd13 键值:value
键名:1123 键值:lslgsgl
本文介绍了如何在Dictionary中实现正反向排序。由于SortedDictionary仅支持正序,反序需要自定义方法。在Web环境下,通过引用System.Linq和System.Collections.Generic,结合LINQ表达式,可以实现Dictionary的反向排序。示例代码展示了正序和反序排序的效果。

1881

被折叠的 条评论
为什么被折叠?



