C#Dictionary排序

 Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
            MyDictionary.Add("第一",1);
            MyDictionary.Add("第四", 4);
            MyDictionary.Add("第三", 3);
            MyDictionary.Add("第二", 2);

            List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(MyDictionary);

            //按照从大到小排序
            lst.Sort(delegate (KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
            {
                return s2.Value.CompareTo(s1.Value);
            });
            ////按照从小到大排序
            //lst.Sort(delegate (KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
            //{
            //    return s2.Value.CompareTo(s1.Value);
            //});
            for (int i = 0; i < lst.Count; i++)
            {
                Console.WriteLine(lst[i].Key);
            }

猜你喜欢

转载自blog.csdn.net/weixin_40068689/article/details/81560454