C# 键值对数据排序代码

时间:2021-05-20

复制代码 代码如下:
public static void SortDicWithLinq(){
Dictionary<DateTime, String> dd = new Dictionary<DateTime, String>();
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<DateTime, String> dicAsc = dd.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
Console.WriteLine("Asc===============");
travelDicKeyDate(dicAsc);


Dictionary<DateTime, String> dicDesc = dd.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
Console.WriteLine("Desc===============");
travelDicKeyDate(dicDesc);
} public static void travelDicKeyDate(Dictionary<DateTime, String> dic)
{
foreach (KeyValuePair<DateTime,String> 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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章