using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Ips.Library.Basic { public static class DictionaryExtensions { internal static bool TryGetValue(this IDictionary dictionary, string key, out T value) { object valueObj; if (dictionary.TryGetValue(key, out valueObj) && valueObj is T) { value = (T)valueObj; return true; } value = default; return false; } public static TValue GetOrDefault(this Dictionary dictionary, TKey key) { TValue obj; return dictionary.TryGetValue(key, out obj) ? obj : default; } public static TValue GetOrDefault(this IDictionary dictionary, TKey key) { return dictionary.TryGetValue(key, out var obj) ? obj : default; } public static TValue GetOrDefault(this IReadOnlyDictionary dictionary, TKey key) { return dictionary.TryGetValue(key, out var obj) ? obj : default; } public static TValue GetOrDefault(this ConcurrentDictionary dictionary, TKey key) { return dictionary.TryGetValue(key, out var obj) ? obj : default; } public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func factory) { TValue obj; if (dictionary.TryGetValue(key, out obj)) { return obj; } return dictionary[key] = factory(key); } public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func factory) { return dictionary.GetOrAdd(key, k => factory()); } public static TValue GetOrAdd(this ConcurrentDictionary dictionary, TKey key, Func factory) { return dictionary.GetOrAdd(key, k => factory()); } } }