标签:
下面是dictionary的扩展
1 using System.Collections.Generic; 2 3 namespace NetAnalysis.Common 4 { 5 6 public static class DictionaryExtensionMethodClass 7 { 8 /// <summary> 9 /// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常 10 /// </summary> 11 public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value) 12 { 13 if (dict.ContainsKey(key) == false) 14 dict.Add(key, value); 15 return dict; 16 } 17 18 19 /// <summary> 20 /// 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换 21 /// </summary> 22 public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value) 23 { 24 dict[key] = value; 25 return dict; 26 } 27 28 /// <summary> 29 /// 获取与指定的键相关联的值,如果没有则返回输入的默认值 30 /// </summary> 31 public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue) 32 { 33 return dict.ContainsKey(key) ? dict[key] : defaultValue; 34 } 35 36 /// <summary> 37 /// 向字典中批量添加键值对 38 /// </summary> 39 /// <param name="replaceExisted">如果已存在,是否替换</param> 40 public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> 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 }
标签:
原文地址:http://www.cnblogs.com/billly/p/5365002.html