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