Neg_Utils/Collections/DictionaryExtensions.cs
2022-12-19 13:54:07 +00:00

42 lines
1.4 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;
}
else
{
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 V value))
{
return value;
}
dict.Add(key, defaultValue);
return defaultValue;
}
}
}