zoukankan      html  css  js  c++  java
  • 字典Dictionary

    Dictionary字典排序

    对一个Dictionary<TKey, TValue>进行排序可以用LINQ:

    Dictionary<string, string> MyDictionary = new Dictionary<string, string>();


    1、键排序

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

    2、值排序

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

    Dictionary字典替换键的值

    var dict = new Dictionary<string,string>();
        dict.Add("abc","1");    
        dict.Add("abcd","2");   
        dict.Add("abcf","3");
        
        //将键值为"abc"的键改为"abce"
        dict = dict.ToDictionary(k => k.Key == "abc" ? "abce" : k.Key, k => k.Value);

    Dictionary字典修改部分键

    var dict = new Dictionary<int,string>();
        dict.Add(1,"1");    
        dict.Add(2,"2");   
        dict.Add(3,"3");
        
        //将键值大于1的键增加1
        dict = dict.ToDictionary(k => k.Key > 1? k.Key +1 : k.Key, k => k.Value);

    // 有相同的键则覆盖,没有则新增键和值

    ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();

    dictionary.AddOrUpdate(key, value, (oldkey, oldvalue) => value);



  • 相关阅读:
    bzoj2959
    学习笔记::lct
    bzoj3203
    bzoj1319
    bzoj3625
    bzoj3992
    bzoj1565
    bzoj3513
    平常练习动归(1.胖男孩)———最长公共子序列
    2016 noip 复赛 day2
  • 原文地址:https://www.cnblogs.com/code1992/p/9759249.html
Copyright © 2011-2022 走看看