1
0

DictionaryExtensions.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 obj;
  13. if (dictionary.TryGetValue(key, out obj))
  14. {
  15. return obj;
  16. }
  17. return dictionary[key] = factory(key);
  18. }
  19. public static TValue GetOrAdd<TKey, TValue>(
  20. this IDictionary<TKey, TValue> dictionary,
  21. TKey key,
  22. Func<TValue> factory)
  23. {
  24. return dictionary.GetOrAdd(key, k => factory());
  25. }
  26. public static TValue AddOrUpdate<TKey, TValue>(
  27. this IDictionary<TKey, TValue> dictionary,
  28. TKey key,
  29. Func<TKey, TValue> addFactory,
  30. Func<TKey, TValue, TValue> updateFactory)
  31. {
  32. TValue obj;
  33. if (dictionary.TryGetValue(key, out obj))
  34. {
  35. obj = updateFactory(key, obj);
  36. }
  37. else
  38. {
  39. obj = addFactory(key);
  40. }
  41. dictionary[key] = obj;
  42. return obj;
  43. }
  44. public static TValue AddOrUpdate<TKey, TValue>(
  45. this IDictionary<TKey, TValue> dictionary,
  46. TKey key,
  47. Func<TValue> addFactory,
  48. Func<TValue, TValue> updateFactory)
  49. {
  50. return dictionary.AddOrUpdate(key, k => addFactory(), (k, v) => updateFactory(v));
  51. }
  52. }
  53. }