| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using System;
- using System.Collections.Generic;
- namespace Masuit.Tools
- {
- public static class IDictionaryExtensions
- {
- /// <summary>
- /// 添加或更新键值对
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="this"></param>
- /// <param name="key">键</param>
- /// <param name="value">值</param>
- /// <returns></returns>
- public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, TValue value)
- {
- if ([email protected](key))
- {
- @this.Add(new KeyValuePair<TKey, TValue>(key, value));
- }
- else
- {
- @this[key] = value;
- }
- return @this[key];
- }
- /// <summary>
- /// 添加或更新键值对
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="this"></param>
- /// <param name="key">键</param>
- /// <param name="addValue">添加时的值</param>
- /// <param name="updateValueFactory">更新时的操作</param>
- /// <returns></returns>
- public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
- {
- if ([email protected](key))
- {
- @this.Add(new KeyValuePair<TKey, TValue>(key, addValue));
- }
- else
- {
- @this[key] = updateValueFactory(key, @this[key]);
- }
- return @this[key];
- }
- /// <summary>
- /// 添加或更新键值对
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="this"></param>
- /// <param name="key">键</param>
- /// <param name="addValueFactory">添加时的操作</param>
- /// <param name="updateValueFactory">更新时的操作</param>
- /// <returns></returns>
- public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
- {
- if ([email protected](key))
- {
- @this.Add(new KeyValuePair<TKey, TValue>(key, addValueFactory(key)));
- }
- else
- {
- @this[key] = updateValueFactory(key, @this[key]);
- }
- return @this[key];
- }
- /// <summary>
- /// 遍历IEnumerable
- /// </summary>
- /// <param name="dic"></param>
- /// <param name="action">回调方法</param>
- public static void ForEach<TKey, TValue>(this IDictionary<TKey, TValue> dic, Action<TKey, TValue> action)
- {
- foreach (var item in dic)
- {
- action(item.Key, item.Value);
- }
- }
- }
- }
|