Merge branch 'dictionary-extensions' into 'main'
dictionary extensions See merge request negames/NegUtils!2
This commit is contained in:
commit
f728f30920
8
Collections.meta
Normal file
8
Collections.meta
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9b25b74f42726e94585fe6ae4b9dd947
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
41
Collections/DictionaryExtensions.cs
Normal file
41
Collections/DictionaryExtensions.cs
Normal file
@ -0,0 +1,41 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Collections/DictionaryExtensions.cs.meta
Normal file
11
Collections/DictionaryExtensions.cs.meta
Normal file
@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a2c99d7a9a2f8184f8b8e94c01723ec6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Loading…
x
Reference in New Issue
Block a user