Init
This commit is contained in:
30
ConsoleApp2/Helpers/Extensions.Dictionary.cs
Normal file
30
ConsoleApp2/Helpers/Extensions.Dictionary.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
namespace ConsoleApp2.Helpers;
|
||||
|
||||
public static class DictionaryExtensions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的键是否存在来添加或是更新字典
|
||||
/// </summary>
|
||||
/// <param name="this"></param>
|
||||
/// <param name="key">指定的键</param>
|
||||
/// <param name="addValue">如果指定的键不存在,则向字典添加该值</param>
|
||||
/// <param name="updateFactory">如果指定的键存在,则根据该委托的返回值修改字典中对应的值</param>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <returns>添加或是修改后的值</returns>
|
||||
public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, TValue addValue,
|
||||
Func<TKey, TValue, TValue> updateFactory)
|
||||
{
|
||||
if (!@this.TryGetValue(key, out var value))
|
||||
{
|
||||
@this.Add(key, addValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
@this[key] = updateFactory(key, value);
|
||||
}
|
||||
|
||||
return @this[key];
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user