欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 键值对数据排序代码

程序员文章站 2024-02-14 17:35:28
复制代码 代码如下:public static void sortdicwithlinq(){      &nb...

复制代码 代码如下:

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