Dictionary按Key正反排序

來源:互聯網
上載者:User
 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.