mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-01-11 19:44:55 +00:00
feat: Added a dictionary extension method for getting or adding a new value via func
This commit is contained in:
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
|
||||
- Added a method for determining if a culture uses 24 hour format
|
||||
- Added math util method for modulus
|
||||
- Added TimeSpan extension methods for cycling hours and minutes without modifying the day
|
||||
- Added a dictionary extension method for getting or adding a new value via func
|
||||
|
||||
### Changed
|
||||
- The Root Config path in Net Standard will now be the ICD.Connect folder in the current environments ProgramData directory
|
||||
|
||||
@@ -147,14 +147,38 @@ namespace ICD.Common.Utils.Extensions
|
||||
if (extends == null)
|
||||
throw new ArgumentNullException("extends");
|
||||
|
||||
// ReSharper disable once CompareNonConstrainedGenericWithNull
|
||||
// ReSharper disable CompareNonConstrainedGenericWithNull
|
||||
if (key == null)
|
||||
// ReSharper restore CompareNonConstrainedGenericWithNull
|
||||
throw new ArgumentNullException("key");
|
||||
|
||||
return extends.GetOrAddNew(key, () => ReflectionUtils.CreateInstance<TValue>());
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <param name="valueFunc"></param>
|
||||
/// <returns></returns>
|
||||
[PublicAPI]
|
||||
public static TValue GetOrAddNew<TKey, TValue>(this IDictionary<TKey, TValue> extends, TKey key, Func<TValue> valueFunc)
|
||||
{
|
||||
if (extends == null)
|
||||
throw new ArgumentNullException("extends");
|
||||
|
||||
// ReSharper disable CompareNonConstrainedGenericWithNull
|
||||
if (key == null)
|
||||
// ReSharper restore CompareNonConstrainedGenericWithNull
|
||||
throw new ArgumentNullException("key");
|
||||
|
||||
TValue value;
|
||||
if (!extends.TryGetValue(key, out value))
|
||||
{
|
||||
value = ReflectionUtils.CreateInstance<TValue>();
|
||||
value = valueFunc();
|
||||
extends.Add(key, value);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user