下面是dictionary的扩展
1 using System.Collections.Generic; 2 3 namespace NetAnalysis.Common 4 { 5 6 public static class DictionaryExtensionMethodClass 7 { 8 ///9 /// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常10 /// 11 public static DictionaryTryAdd (this Dictionary dict, TKey key, TValue value)12 {13 if (dict.ContainsKey(key) == false)14 dict.Add(key, value);15 return dict;16 }17 18 19 /// 20 /// 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换21 /// 22 public static DictionaryAddOrPeplace (this Dictionary dict, TKey key, TValue value)23 {24 dict[key] = value;25 return dict;26 }27 28 /// 29 /// 获取与指定的键相关联的值,如果没有则返回输入的默认值30 /// 31 public static TValue GetValue(this Dictionary dict, TKey key, TValue defaultValue)32 {33 return dict.ContainsKey(key) ? dict[key] : defaultValue;34 }35 36 /// 37 /// 向字典中批量添加键值对38 /// 39 /// 如果已存在,是否替换40 public static DictionaryAddRange (this Dictionary dict, IEnumerable > values, bool replaceExisted)41 {42 foreach (var item in values)43 {44 if (dict.ContainsKey(item.Key) == false || replaceExisted)45 dict[item.Key] = item.Value;46 }47 return dict;48 49 }50 51 }52 }