DictionaryExtensions.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. namespace Ips.Library.Basic
  5. {
  6. public static class DictionaryExtensions
  7. {
  8. internal static bool TryGetValue<T>(this IDictionary<string, object> dictionary, string key, out T value)
  9. {
  10. object valueObj;
  11. if (dictionary.TryGetValue(key, out valueObj) && valueObj is T)
  12. {
  13. value = (T)valueObj;
  14. return true;
  15. }
  16. value = default;
  17. return false;
  18. }
  19. public static TValue GetOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
  20. {
  21. TValue obj;
  22. return dictionary.TryGetValue(key, out obj) ? obj : default;
  23. }
  24. public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
  25. {
  26. return dictionary.TryGetValue(key, out var obj) ? obj : default;
  27. }
  28. public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
  29. {
  30. return dictionary.TryGetValue(key, out var obj) ? obj : default;
  31. }
  32. public static TValue GetOrDefault<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
  33. {
  34. return dictionary.TryGetValue(key, out var obj) ? obj : default;
  35. }
  36. public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> factory)
  37. {
  38. TValue obj;
  39. if (dictionary.TryGetValue(key, out obj))
  40. {
  41. return obj;
  42. }
  43. return dictionary[key] = factory(key);
  44. }
  45. public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> factory)
  46. {
  47. return dictionary.GetOrAdd(key, k => factory());
  48. }
  49. public static TValue GetOrAdd<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> factory)
  50. {
  51. return dictionary.GetOrAdd(key, k => factory());
  52. }
  53. }
  54. }