Dictionary<string, int> dic = new Dictionary<string, int>();内容为:
张三 5
老刘 0
李四 7
王二 1
李天天 5
.
.
.
需要排序为:
老刘 0
王二 1
张三 5
李天天 5
李四 7网上找了很多资料都无法实现,求高手指导。      Dictionary排序

解决方案 »

  1.   

    http://hi.baidu.com/pctonc/item/5fd3fee9585e68205a2d64a0
      

  2.   

    static void Main(string[] args)
            {
                Dictionary<string, int> dic = new Dictionary<string, int>();
                dic.Add("张三", 5);
                dic.Add("老刘", 0);
                dic.Add("李四", 7);
                dic.Add("王二", 1);
                dic.Add("李天天", 5);            var result = dic.OrderBy(x => x.Value);
                result.ToList().ForEach(x => Console.WriteLine(string.Join(" ", x.Key, x.Value)));
            }
      

  3.   

    非常谢谢,我现在要将排序后的键和值放入新的字典result.ToList().ForEach(x => NewDicCount.Add(x.Key, x.Value));这样为何不行啊,排序还是没变,编程基础不是很扎实,后面那句改不了...
      

  4.   

    你这样是可以的啊,我刚试过了, NewDicCount是排好序的。
      

  5.   

    直接用result转一下吧 NewDicCount = result.ToDictionary(o => o.Key, o => o.Value);
      

  6.   

    你这样是可以的啊,我刚试过了, NewDicCount是排好序的。                Dictionary<string, string> dicCount = new Dictionary<string, string>();
                    Dictionary<string, string> NewDicCount = new Dictionary<string, string>();
                    foreach (DataRow rowUser in dtUserName.Rows)
                    {
                        string userCount = GetTodoCount(rowUser["user_id"].ToString());
                        dicCount.Add(rowUser["user_name"].ToString(),userCount);
                    }                var result = dicCount.OrderByDescending(x => x.Value);
                    result.ToList().ForEach(x => NewDicCount.Add(x.Key, x.Value));                foreach (string keyCount in NewDicCount.Keys)
                    {
                        sb.AppendFormat("{0}", "<tr>");
                        sb.AppendFormat("{0}{1}{2}", "<td><font size=2><center>", keyCount, "</center></font></td>");
                        sb.AppendFormat("{0}{1}{2}", "<td><font size=2><center>", "<a href=\"http://tms.paidui.com.cn/App/Todo\">" + NewDicCount[keyCount] + "</a>", "</center></font></td>");
                        sb.AppendFormat("{0}", "</tr>");
                    } 您看下这样是否有问题不?输出的结果还是没有排序的
      

  7.   

    是的,也可以直接转。
    var result = dic.OrderBy(x => x.Value);
    Dictionary<string, int> newdic = result.ToDictionary(x => x.Key, x => x.Value);
      

  8.   

    非常谢谢,w问题解决了,是我写错了,Dictionary<string, string> dicCount = new Dictionary<string, string>();应该为Dictionary<string, int> dicCount = new Dictionary<string, int>();
      

  9.   


    .NET 2.0 怎么解决?
      

  10.   


    .NET 2.0 怎么解决?
    不就是一个排序吗?自己定义一个排序算法(快排、冒泡等等)就可以了。比如:http://zhidao.baidu.com/link?url=GqB0egZWPIZRSFLJo2Xf0tkXvo7iIa0zGTHDccGtVs6NvST6XkXlwgiwIfrf2uoRXcKhoIIHxYUclp0Ij64EJa