C# Dictionary(字典)的键、值排序 进行值排序可以用LINQ

  1. 对一个Dictionary进行值排序可以用LINQ:  
      
    Dictionary MyDictionary = new Dictionary();  
      
    MyDictionary = (from entry in MyDictionary   
                                         orderby entry.Value ascending  
                                         select entry).ToDictionary(pair => pair.Key, pair => pair.Value);  



Dictionary dic1 = new Dictionary();

      dic1.Add("ddd","123");
      dic1.Add("aaa", "123");
      dic1.Add("ccc", "123");
      dic1.Add("fff", "123");
      dic1.Add("eee", "123");
      dic1.Add("bbb", "123");
      Dictionary dic1Asc = dic1.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
      Dictionary dic1desc = dic1.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);

      Dictionary dic1Asc1
        = (from d in dic1
           orderby d.Key ascending
           select d).ToDictionary(k => k.Key, v => v.Value);
      Dictionary dic1desc2
        = (from d in dic1
           orderby d.Key descending 
           select d).ToDictionary(k => k.Key, v => v.Value);


      List list = new List();
      list.Add("aaa");
      list.Add("ddd");
      list.Add("bbb");
      list.Add("ccc");
      list.Add("bbb");
      var ascList = list.OrderBy(o => o);
      var descList = list.OrderByDescending(o => o);

      var ascList1 = (from l in list
                      orderby l ascending
                      select l).ToList();
      var descList2 = (from l in list
                       orderby l descending
                       select l).ToList();
      string str = "";


你可能感兴趣的:(LINQ,C#,LINQ,dictionary)