使用過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