using System; using System.Collections.Generic; namespace SK.Framework { public static class DictionaryExtension { public static Dictionary Copy(this Dictionary self) { Dictionary retDic = new Dictionary(self.Count); using (var dicE = self.GetEnumerator()) { while (dicE.MoveNext()) { retDic.Add(dicE.Current.Key, dicE.Current.Value); } } return retDic; } public static Dictionary ForEach(this Dictionary self, Action action) { using(var dicE = self.GetEnumerator()) { while (dicE.MoveNext()) { action(dicE.Current.Key, dicE.Current.Value); } } return self; } /// /// 合并字典 /// /// 键类型 /// 值类型 /// 字典 /// 被合并的字典 /// 若存在相同键,是否覆盖对应值 /// 合并后的字典 public static Dictionary AddRange(this Dictionary self, Dictionary target, bool isOverride = false) { using(var dicE = target.GetEnumerator()) { while (dicE.MoveNext()) { var current = dicE.Current; if (self.ContainsKey(current.Key)) { if (isOverride) { self[current.Key] = current.Value; continue; } } self.Add(current.Key, current.Value); } } return self; } /// /// 将字典的所有值放入一个列表 /// /// 键类型 /// 值类型 /// 字典 /// 列表 public static List Value2List(this Dictionary self) { List retList = new List(self.Count); foreach (var kv in self) { retList.Add(kv.Value); } return retList; } /// /// 将字典的所有值放入一个数组 /// /// 键类型 /// 值类型 /// 字典 /// 数组 public static V[] Value2Array(this Dictionary self) { V[] retArray = new V[self.Count]; int index = -1; foreach (var kv in self) { retArray[++index] = kv.Value; } return retArray; } /// /// 尝试添加 /// /// 键类型 /// 值类型 /// 字典 /// 键 /// 值 /// 若不存在相同键,添加成功并返回true,否则返回false public static bool TryAdd(this Dictionary self, K k, V v) { if (!self.ContainsKey(k)) { self.Add(k, v); return true; } return false; } } }