DictionaryExtensions.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Admin.Core.Common.Extensions
  4. {
  5. public static class DictionaryExtensions
  6. {
  7. public static TValue GetOrAdd<TKey, TValue>(
  8. this IDictionary<TKey, TValue> dictionary,
  9. TKey key,
  10. Func<TKey, TValue> factory)
  11. {
  12. TValue value;
  13. if (!dictionary.TryGetValue(key, out value))
  14. {
  15. value = factory(key);
  16. dictionary.Add(key, value);
  17. }
  18. return value;
  19. }
  20. public static TValue GetOrAdd<TKey, TValue>(
  21. this IDictionary<TKey, TValue> dictionary,
  22. TKey key,
  23. Func<TValue> factory)
  24. {
  25. TValue value;
  26. if (!dictionary.TryGetValue(key, out value))
  27. {
  28. value = factory();
  29. dictionary.Add(key, value);
  30. }
  31. return value;
  32. }
  33. public static TValue AddOrUpdate<TKey, TValue>(
  34. this IDictionary<TKey, TValue> dictionary,
  35. TKey key,
  36. Func<TKey, TValue> addFactory,
  37. Func<TKey, TValue, TValue> updateFactory)
  38. {
  39. TValue value;
  40. if (dictionary.TryGetValue(key, out value))
  41. {
  42. value = updateFactory(key, value);
  43. }
  44. else
  45. {
  46. value = addFactory(key);
  47. }
  48. dictionary[key] = value;
  49. return value;
  50. }
  51. public static TValue AddOrUpdate<TKey, TValue>(
  52. this IDictionary<TKey, TValue> dictionary,
  53. TKey key,
  54. Func<TValue> addFactory,
  55. Func<TValue, TValue> updateFactory)
  56. {
  57. TValue value;
  58. if (dictionary.TryGetValue(key, out value))
  59. {
  60. value = updateFactory(value);
  61. }
  62. else
  63. {
  64. value = addFactory();
  65. }
  66. dictionary[key] = value;
  67. return value;
  68. }
  69. }
  70. }