字典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);



posted @ 2018-10-09 11:16  quanzhan  阅读(247)  评论(0编辑  收藏  举报