Neg_Utils/Collections/DictionaryExtensions.cs
2022-12-16 21:29:30 +01:00

42 lines
1.2 KiB
C#

using System.Collections.Generic;
namespace NEG.Utils.Collections
{
public static class DictionaryExtensions
{
/// <summary>
/// Adds an element to a dictionary if there was none assigned to specified <paramref name="key"/>, otherwise replaces the existing
/// </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 sets it if there was no assoiation then return the associated value
/// </summary>
/// <returns></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;
}
}
}