mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-04-12 12:07:05 +00:00
feat: Adding extension method for getting or adding a new item to a dictionary
This commit is contained in:
parent
94ac37b32a
commit
66f4e797ed
1 changed files with 29 additions and 1 deletions
|
|
@ -112,7 +112,6 @@ namespace ICD.Common.Utils.Extensions
|
||||||
/// <param name="key"></param>
|
/// <param name="key"></param>
|
||||||
/// <param name="defaultValue"></param>
|
/// <param name="defaultValue"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[CanBeNull]
|
|
||||||
[PublicAPI]
|
[PublicAPI]
|
||||||
public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> extends, TKey key,
|
public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> extends, TKey key,
|
||||||
TValue defaultValue)
|
TValue defaultValue)
|
||||||
|
|
@ -130,6 +129,35 @@ namespace ICD.Common.Utils.Extensions
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// If the key is present in the dictionary return the value, otherwise add a new value to the dictionary and return it.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="TKey"></typeparam>
|
||||||
|
/// <typeparam name="TValue"></typeparam>
|
||||||
|
/// <param name="extends"></param>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[PublicAPI]
|
||||||
|
public static TValue GetOrAddNew<TKey, TValue>(this IDictionary<TKey, TValue> extends, TKey key)
|
||||||
|
where TValue : new()
|
||||||
|
{
|
||||||
|
if (extends == null)
|
||||||
|
throw new ArgumentNullException("extends");
|
||||||
|
|
||||||
|
// ReSharper disable once CompareNonConstrainedGenericWithNull
|
||||||
|
if (key == null)
|
||||||
|
throw new ArgumentNullException("key");
|
||||||
|
|
||||||
|
TValue value;
|
||||||
|
if (!extends.TryGetValue(key, out value))
|
||||||
|
{
|
||||||
|
value = ReflectionUtils.CreateInstance<TValue>();
|
||||||
|
extends.Add(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets a key for the given value.
|
/// Gets a key for the given value.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue