// /***********************************************************
// * 项目名称: YunDouTax.BaseLib
// * 文件名称: DictionaryExtension.cs
// * 功能描述:
// * 代码作者: 云勇
// * 创建时间: 2017年12月18日 14:50
// * 更新时间: 2017年12月18日 14:50
// ************************************************************/
using System.Collections.Generic;
namespace YunDouTax.BaseLib.Extensions
{
/// <summary>
///
/// </summary>
public static class DictionaryExtension
{
/// <summary>
/// 如果不存在则添加
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool AddIfNotExist<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
return false;
}
dictionary.Add(key, value);
return true;
}
/// <summary>
/// 如果存在则更新
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool UpdateIfExist<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (!dictionary.ContainsKey(key))
{
return false;
}
dictionary[key] = value;
return true;
}
/// <summary>
/// 添加或更新元素
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
dictionary[key] = value;
}
else
{
dictionary.Add(key, value);
}
}
}
}
Dictionary扩展方法
最新推荐文章于 2024-08-29 17:46:16 发布