using System;
using System.Collections.Generic;
namespace Unosquare.Swan {
///
/// Extension methods.
///
public static partial class Extensions {
///
/// Gets the value if exists or default.
///
/// The type of the key.
/// The type of the value.
/// The dictionary.
/// The key.
/// The default value.
///
/// The value of the provided key or default.
///
/// dict.
public static TValue GetValueOrDefault(this IDictionary dict, TKey key, TValue defaultValue = default) {
if(dict == null) {
throw new ArgumentNullException(nameof(dict));
}
return dict.ContainsKey(key) ? dict[key] : defaultValue;
}
///
/// Adds a key/value pair to the Dictionary if the key does not already exist.
/// If the value is null, the key will not be updated.
///
/// Based on ConcurrentDictionary.GetOrAdd method.
///
/// The type of the key.
/// The type of the value.
/// The dictionary.
/// The key.
/// The value factory.
/// The value for the key.
public static TValue GetOrAdd(this IDictionary dict, TKey key, Func valueFactory) {
if(dict == null) {
throw new ArgumentNullException(nameof(dict));
}
if(!dict.ContainsKey(key)) {
TValue value = valueFactory(key);
if(Equals(value, default)) {
return default;
}
dict[key] = value;
}
return dict[key];
}
///
/// Executes the item action for each element in the Dictionary.
///
/// The type of the key.
/// The type of the value.
/// The dictionary.
/// The item action.
/// dict.
public static void ForEach(this IDictionary dict, Action itemAction) {
if(dict == null) {
throw new ArgumentNullException(nameof(dict));
}
foreach(KeyValuePair kvp in dict) {
itemAction(kvp.Key, kvp.Value);
}
}
}
}