C# 字典的扩展方法

        /// <summary>
        /// 根据条件删除字典中所有符合的键值对
        /// </summary>
        /// <returns></returns>
        public static int RemoveAll<TKey, TValue>(this IDictionary<TKey, TValue> source, Func<TKey, TValue, bool> predicate)
        {
            List<TKey> listTKey = new List<TKey>();
            foreach (KeyValuePair<TKey, TValue> kv in source)
            {
                if (predicate(kv.Key, kv.Value))
                {
                    listTKey.Add(kv.Key);
                }
            }
            foreach (TKey k in listTKey)
            {
                source.Remove(k);
            }
            return listTKey.Count;
        }

        /// <summary>
        /// 判断字典中是否存在符合条件的键值对
        /// </summary>
        public static bool Exists<TKey, TValue>(this IDictionary<TKey, TValue> source, Func<TKey, TValue, bool> predicate)
        {
            List<TKey> listTKey = new List<TKey>();
            foreach (KeyValuePair<TKey, TValue> kv in source)
            {
                if (predicate(kv.Key, kv.Value))
                {
                    return true;
                }
            }
            return false;
        }
发布了31 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/breakbridge/article/details/102976116
今日推荐