C# 键值对数据排序代码
本文导语: 代码如下:public static void SortDicWithLinq(){ Dictionary dd = new Dictionary(); DateTime dt = DateTime.Now; dd.Add(dt, "bbb"); dd.Add(dt.AddDays(-1),"ccc"); dd.Add(dt.AddDays(1), "aa...
public static void SortDicWithLinq(){
Dictionary dd = new Dictionary();
DateTime dt = DateTime.Now;
dd.Add(dt, "bbb");
dd.Add(dt.AddDays(-1),"ccc");
dd.Add(dt.AddDays(1), "aaa");
Console.WriteLine("Org===============");
travelDicKeyDate(dd);
Dictionary dicAsc = dd.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
Console.WriteLine("Asc===============");
travelDicKeyDate(dicAsc);
Dictionary dicDesc = dd.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
Console.WriteLine("Desc===============");
travelDicKeyDate(dicDesc);
} public static void travelDicKeyDate(Dictionary dic)
{
foreach (KeyValuePair kvp in dic)
{
Console.WriteLine(String.Format("{0} {1}",kvp.Key,kvp.Value));
}
}
output:
Org===============
2013/9/27 11:07:29 bbb
2013/9/26 11:07:29 ccc
2013/9/28 11:07:29 aaa
Asc===============
2013/9/26 11:07:29 ccc
2013/9/27 11:07:29 bbb
2013/9/28 11:07:29 aaa
Desc===============
2013/9/28 11:07:29 aaa
2013/9/27 11:07:29 bbb
2013/9/26 11:07:29 ccc