using System; using System.Collections.Generic; using System.Windows; namespace HandyControl.Expression.Drawing { internal static class CommonExtensions { public static void AddRange(this ICollection collection, IEnumerable newItems) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (collection is List list) { list.AddRange(newItems); } else { foreach (var local in newItems) { collection.Add(local); } } } public static bool SetIfDifferent(this DependencyObject dependencyObject, DependencyProperty dependencyProperty, object value) { if (!Equals(dependencyObject.GetValue(dependencyProperty), value)) { dependencyObject.SetValue(dependencyProperty, value); return true; } return false; } public static bool EnsureListCount(this IList list, int count, Func factory = null) { if (list == null) { throw new ArgumentNullException(nameof(list)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (!list.EnsureListCountAtLeast(count, factory)) { if (list.Count <= count) { return false; } if (list is List list2) { list2.RemoveRange(count, list.Count - count); } else { for (int i = list.Count - 1; i >= count; i--) { list.RemoveAt(i); } } } return true; } public static bool EnsureListCountAtLeast(this IList list, int count, Func factory = null) { if (list == null) { throw new ArgumentNullException(nameof(list)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (list.Count >= count) { return false; } if ((list is List list2) && (factory == null)) { list2.AddRange(new T[count - list.Count]); } else { for (int i = list.Count; i < count; i++) { list.Add((factory == null) ? default(T) : factory()); } } return true; } public static bool ClearIfSet(this DependencyObject dependencyObject, DependencyProperty dependencyProperty) { if (dependencyObject.ReadLocalValue(dependencyProperty) != DependencyProperty.UnsetValue) { dependencyObject.ClearValue(dependencyProperty); return true; } return false; } public static void RemoveLast(this IList list) { list.RemoveAt(list.Count - 1); } } }