IDictionaryExtensions.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Masuit.Tools
  4. {
  5. public static class IDictionaryExtensions
  6. {
  7. /// <summary>
  8. /// 添加或更新键值对
  9. /// </summary>
  10. /// <typeparam name="TKey"></typeparam>
  11. /// <typeparam name="TValue"></typeparam>
  12. /// <param name="this"></param>
  13. /// <param name="key">键</param>
  14. /// <param name="value">值</param>
  15. /// <returns></returns>
  16. public static TValue AddOrUpdate<TKey, TValue>(
  17. this IDictionary<TKey, TValue> @this,
  18. TKey key,
  19. TValue value)
  20. {
  21. if ([email protected](key))
  22. {
  23. @this.Add(new KeyValuePair<TKey, TValue>(key, value));
  24. }
  25. else
  26. {
  27. @this[key] = value;
  28. }
  29. return @this[key];
  30. }
  31. /// <summary>
  32. /// 添加或更新键值对
  33. /// </summary>
  34. /// <typeparam name="TKey"></typeparam>
  35. /// <typeparam name="TValue"></typeparam>
  36. /// <param name="this"></param>
  37. /// <param name="key">键</param>
  38. /// <param name="addValue">添加时的值</param>
  39. /// <param name="updateValueFactory">更新时的操作</param>
  40. /// <returns></returns>
  41. public static TValue AddOrUpdate<TKey, TValue>(
  42. this IDictionary<TKey, TValue> @this,
  43. TKey key,
  44. TValue addValue,
  45. Func<TKey, TValue, TValue> updateValueFactory)
  46. {
  47. if ([email protected](key))
  48. {
  49. @this.Add(new KeyValuePair<TKey, TValue>(key, addValue));
  50. }
  51. else
  52. {
  53. @this[key] = updateValueFactory(key, @this[key]);
  54. }
  55. return @this[key];
  56. }
  57. /// <summary>
  58. /// 添加或更新键值对
  59. /// </summary>
  60. /// <typeparam name="TKey"></typeparam>
  61. /// <typeparam name="TValue"></typeparam>
  62. /// <param name="this"></param>
  63. /// <param name="key">键</param>
  64. /// <param name="addValueFactory">添加时的操作</param>
  65. /// <param name="updateValueFactory">更新时的操作</param>
  66. /// <returns></returns>
  67. public static TValue AddOrUpdate<TKey, TValue>(
  68. this IDictionary<TKey, TValue> @this,
  69. TKey key,
  70. Func<TKey, TValue> addValueFactory,
  71. Func<TKey, TValue, TValue> updateValueFactory)
  72. {
  73. if ([email protected](key))
  74. {
  75. @this.Add(new KeyValuePair<TKey, TValue>(key, addValueFactory(key)));
  76. }
  77. else
  78. {
  79. @this[key] = updateValueFactory(key, @this[key]);
  80. }
  81. return @this[key];
  82. }
  83. }
  84. }