38 lines
1.3 KiB
C#
38 lines
1.3 KiB
C#
using System.Collections.Generic;
|
|
|
|
namespace NEG.Utils.Collections
|
|
{
|
|
public static class DictionaryExtensions
|
|
{
|
|
/// <summary>
|
|
/// Adds given value to a dictionary if there was no element at given <paramref name="key" />, replaces element with
|
|
/// <paramref name="value"> otherwise.
|
|
/// </summary>
|
|
/// <returns>true if element was added, false if it was replaced</returns>
|
|
public static bool AddOrUpdate<K, V>(this Dictionary<K, V> dict, K key, V value)
|
|
{
|
|
if (dict.ContainsKey(key))
|
|
{
|
|
dict[key] = value;
|
|
return false;
|
|
}
|
|
|
|
dict.Add(key, value);
|
|
return true;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Gets a value from the dictionary under a specified key or adds it if did not exist and returns
|
|
/// <paramref name="defaultValue" />.
|
|
/// </summary>
|
|
/// <returns>value under a given <paramref name="key" /> if it exists, <paramref name="defaultValue" /> otherwise</returns>
|
|
public static V GetOrSetToDefault<K, V>(this Dictionary<K, V> dict, K key, V defaultValue)
|
|
{
|
|
if (dict.TryGetValue(key, out var value)) return value;
|
|
dict.Add(key, defaultValue);
|
|
|
|
return defaultValue;
|
|
}
|
|
}
|
|
} |