• C# Dictionary 的几种遍历方法,排序


    Dictionary<string, int> list = new Dictionary<string, int>();
     
                list.Add("d", 1);
     
                //3.0以上版本
                foreach (var item in list)
                {
                    Console.WriteLine(item.Key + item.Value);
                }
                //KeyValuePair<T,K>
                foreach (KeyValuePair<string, int> kv in list)
                {
                    Console.WriteLine(kv.Key + kv.Value);
                }
                //通过键的集合取
                foreach (string key in list.Keys)
                {
                    Console.WriteLine(key + list[key]);
                }
                //直接取值
                foreach (int val in list.Values)
                {
                    Console.WriteLine(val);
                } 
                //非要采用for的方法也可
                List<string> test = new List<string>(list.Keys);
     
                for (int i = 0; i < list.Count; i++)
                {
                    Console.WriteLine(test[i] + list[test[i]]);
                }
     
    Dictionary<string, string> dic1Asc = dic1.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
          Dictionary<string, string> dic1desc = dic1.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
    
          Dictionary<string, string> dic1Asc1
            = (from d in dic1
               orderby d.Key ascending
               select d).ToDictionary(k => k.Key, v => v.Value);
          Dictionary<string, string> dic1desc2
            = (from d in dic1
               orderby d.Key descending 
               select d).ToDictionary(k => k.Key, v => v.Value);
    
    
          List<string> list = new List<string>();
          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 = "";
  • 相关阅读:
    CF1394A Boboniu Chats with Du 题解
    P3377 【模板】左偏树(可并堆)题解
    P2152 [SDOI2009]SuperGCD 题解
    在其他模块中调用代码
    教程:创建Go模块
    Go入门
    反悔贪心
    codeforces 1569 E. Playoff Restoration (meet-in-the-middle)
    codeforces 1036 F. Relatively Prime Powers (容斥+精度处理+大数边界处理)
    icpc沈阳2020 H. The Boomsday Project (dp+二分)
  • 原文地址:https://www.cnblogs.com/kennyliu/p/3785451.html
Copyright © 2020-2023  润新知