| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- 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];
- }
- }
- }
|