字典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);
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步