日期:2014-05-18  浏览次数:21254 次

Dictionary如何倒序输出?
C# code

      Dictionary<int, int> dic = new Dictionary<int, int>();
      dic.Add(1, 158);
      dic.Add(5, 25);
      dic.Add(3, 215);
      dic.Add(2, 369);
      dic.Add(4, 147);

      var result = from pair in dic orderby pair.Key select pair;

      foreach (KeyValuePair<int, int> pair in result)
      {
          Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);
      }

      Console.ReadKey();



现在结果是
1
2
3
4
5

我希望是

5
4
3
2
1


------解决方案--------------------
var result = from pair in dic orderby pair.Key descending select pair;
------解决方案--------------------
C# code
Dictionary<int, int> dic = new Dictionary<int, int>();
            dic.Add(1, 158);
            dic.Add(5, 25);
            dic.Add(3, 215);
            dic.Add(2, 369);
            dic.Add(4, 147);

            var result = from pair in dic orderby pair.Key descending select pair;

            foreach (KeyValuePair<int, int> pair in result)
            {
                Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);
            }

            Console.ReadKey();

------解决方案--------------------
呵呵,LINQ基本和SQL一样的。