IDictionaryExtensions.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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>(this IDictionary<TKey, TValue> @this, TKey key, TValue value)
  17. {
  18. if ([email protected](key))
  19. {
  20. @this.Add(new KeyValuePair<TKey, TValue>(key, value));
  21. }
  22. else
  23. {
  24. @this[key] = value;
  25. }
  26. return @this[key];
  27. }
  28. /// <summary>
  29. /// 添加或更新键值对
  30. /// </summary>
  31. /// <typeparam name="TKey"></typeparam>
  32. /// <typeparam name="TValue"></typeparam>
  33. /// <param name="this"></param>
  34. /// <param name="key">键</param>
  35. /// <param name="addValue">添加时的值</param>
  36. /// <param name="updateValueFactory">更新时的操作</param>
  37. /// <returns></returns>
  38. public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
  39. {
  40. if ([email protected](key))
  41. {
  42. @this.Add(new KeyValuePair<TKey, TValue>(key, addValue));
  43. }
  44. else
  45. {
  46. @this[key] = updateValueFactory(key, @this[key]);
  47. }
  48. return @this[key];
  49. }
  50. /// <summary>
  51. /// 添加或更新键值对
  52. /// </summary>
  53. /// <typeparam name="TKey"></typeparam>
  54. /// <typeparam name="TValue"></typeparam>
  55. /// <param name="this"></param>
  56. /// <param name="key">键</param>
  57. /// <param name="addValueFactory">添加时的操作</param>
  58. /// <param name="updateValueFactory">更新时的操作</param>
  59. /// <returns></returns>
  60. public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> @this, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
  61. {
  62. if ([email protected](key))
  63. {
  64. @this.Add(new KeyValuePair<TKey, TValue>(key, addValueFactory(key)));
  65. }
  66. else
  67. {
  68. @this[key] = updateValueFactory(key, @this[key]);
  69. }
  70. return @this[key];
  71. }
  72. /// <summary>
  73. /// 遍历IEnumerable
  74. /// </summary>
  75. /// <param name="dic"></param>
  76. /// <param name="action">回调方法</param>
  77. public static void ForEach<TKey, TValue>(this IDictionary<TKey, TValue> dic, Action<TKey, TValue> action)
  78. {
  79. foreach (var item in dic)
  80. {
  81. action(item.Key, item.Value);
  82. }
  83. }
  84. }
  85. }