用LINQ对Dictionary排序

代码如下 :

        static void Main(string[] args)
        {
            Dictionary<int, int> di = new Dictionary<int, int>();
            di.Add(9, 1);
            di.Add(0, 6);
            di.Add(2, 8);

            var sortedDict = (from entry in di orderby entry.Key ascending select entry)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

            foreach (var pair in di)
            {
                Console.WriteLine("{0},{1}", pair.Key, pair.Value);
            }

            Console.WriteLine("--------------------");

            foreach (var pair in sortedDict)
            {
                Console.WriteLine("{0},{1}", pair.Key, pair.Value);
            }

            Console.ReadLine();
        }

方法来自stackoverflow

http://stackoverflow.com/questions/289/how-do-you-sort-a-c-sharp-dictionary-by-value

posted on 2013-03-25 00:26  齐文宣  阅读(304)  评论(0)    收藏  举报

导航