CommonExtensions.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows;
  4. namespace HandyControl.Expression.Drawing;
  5. internal static class CommonExtensions
  6. {
  7. public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> newItems)
  8. {
  9. if (collection == null)
  10. {
  11. throw new ArgumentNullException(nameof(collection));
  12. }
  13. if (collection is List<T> list)
  14. {
  15. list.AddRange(newItems);
  16. }
  17. else
  18. {
  19. foreach (var local in newItems)
  20. {
  21. collection.Add(local);
  22. }
  23. }
  24. }
  25. public static bool SetIfDifferent(this DependencyObject dependencyObject, DependencyProperty dependencyProperty, object value)
  26. {
  27. if (!Equals(dependencyObject.GetValue(dependencyProperty), value))
  28. {
  29. dependencyObject.SetValue(dependencyProperty, value);
  30. return true;
  31. }
  32. return false;
  33. }
  34. public static bool EnsureListCount<T>(this IList<T> list, int count, Func<T> factory = null)
  35. {
  36. if (list == null)
  37. {
  38. throw new ArgumentNullException(nameof(list));
  39. }
  40. if (count < 0)
  41. {
  42. throw new ArgumentOutOfRangeException(nameof(count));
  43. }
  44. if (!list.EnsureListCountAtLeast(count, factory))
  45. {
  46. if (list.Count <= count)
  47. {
  48. return false;
  49. }
  50. if (list is List<T> list2)
  51. {
  52. list2.RemoveRange(count, list.Count - count);
  53. }
  54. else
  55. {
  56. for (var i = list.Count - 1; i >= count; i--)
  57. {
  58. list.RemoveAt(i);
  59. }
  60. }
  61. }
  62. return true;
  63. }
  64. public static bool EnsureListCountAtLeast<T>(this IList<T> list, int count, Func<T> factory = null)
  65. {
  66. if (list == null)
  67. {
  68. throw new ArgumentNullException(nameof(list));
  69. }
  70. if (count < 0)
  71. {
  72. throw new ArgumentOutOfRangeException(nameof(count));
  73. }
  74. if (list.Count >= count)
  75. {
  76. return false;
  77. }
  78. if ((list is List<T> list2) && factory == null)
  79. {
  80. list2.AddRange(new T[count - list.Count]);
  81. }
  82. else
  83. {
  84. for (var i = list.Count; i < count; i++)
  85. {
  86. list.Add(factory == null ? default : factory());
  87. }
  88. }
  89. return true;
  90. }
  91. public static bool ClearIfSet(this DependencyObject dependencyObject, DependencyProperty dependencyProperty)
  92. {
  93. if (dependencyObject.ReadLocalValue(dependencyProperty) != DependencyProperty.UnsetValue)
  94. {
  95. dependencyObject.ClearValue(dependencyProperty);
  96. return true;
  97. }
  98. return false;
  99. }
  100. public static void RemoveLast<T>(this IList<T> list)
  101. {
  102. list.RemoveAt(list.Count - 1);
  103. }
  104. }