using mbts.utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Reactive.Linq; namespace System.Collections.Generic { public static class EnumerableExtensions { #region Ordered public static IOrderedEnumerable Ordered(this IEnumerable enumerable) => enumerable.OrderBy(t => t); public static IEnumerable Ordered(this IEnumerable enumerable, Func compare) => enumerable.Ordered(Comparer.Create(new Comparison(compare))); public static IEnumerable Ordered(this IEnumerable enumerable, IComparer comparer) => enumerable.OrderBy(t => t, comparer); #endregion public static IEnumerable DistinctOn(this IEnumerable enumerable, Func key_selector) => enumerable.Distinct(EqualityComparer.Create((x, y) => key_selector(x).Equals(key_selector(y)), x => key_selector(x).GetHashCode())); public static IEnumerable Except(this IEnumerable enumerable, IEnumerable second, Func key_selector) => enumerable.Where(t => !second.Contains(key_selector(t))); public static IEnumerable Intersect(this IEnumerable enumerable, IEnumerable second, Func key_selector) => enumerable.Where(t => second.Contains(key_selector(t))); public static T[] ToLArray(this IEnumerable enumerable) => enumerable.ToList().ToArray(); public static TAccumulate AggregateWhile(this IEnumerable source, TAccumulate seed, Func aggregate, Func predicate) { TAccumulate rv = seed; foreach (T el in source) { if (!predicate(rv, el)) break; rv = aggregate(rv, el); } return rv; } public static IEnumerable ToIEnumerable(this T item) { yield return item; } public static IEnumerable TakeWhile(this IEnumerable source, TAccumulate seed, Func accumulate, Func predicate) { TAccumulate a = seed; foreach (T el in source) { if (!predicate(a, el)) break; a = accumulate(a, el); yield return el; } } public static bool TryGetFirst(this IEnumerable source, Func predicate, out T result) { if (source == null) throw new ArgumentNullException(nameof(source)); foreach (T element in source) if (predicate(element)) { result = element; return true; } result = default; return false; } public static bool TryGetFirst(this IEnumerable source, Func predicate, Func select, out TResult result) { if (source == null) throw new ArgumentNullException(nameof(source)); foreach (T element in source) if (predicate(element)) { result = select(element); return true; } result = default; return false; } public static T FirstOrDefault(this IEnumerable source, Func predicate, T default_rv) { if (source == null) throw new ArgumentNullException(nameof(source)); foreach (T element in source) if (predicate(element)) return element; return default_rv; } public static TResult FirstOrDefault(this IEnumerable source, Func predicate, Func select) { if (source == null) throw new ArgumentNullException(nameof(source)); foreach (T element in source) if (predicate(element)) return select(element); return default; } public static TResult FirstOrDefault(this IEnumerable source, Func predicate, Func select, TResult default_rv) { if (source == null) throw new ArgumentNullException(nameof(source)); foreach (T element in source) if (predicate(element)) return select(element); return default_rv; } public static T LastOrDefault(this IEnumerable source, T default_rv) { if (source == null) throw new ArgumentNullException(nameof(source)); var list = source as IList; if (list != null) { int count = list.Count; if (count > 0) return list[count - 1]; } else { using (var e = source.GetEnumerator()) if (e.MoveNext()) { T result; do result = e.Current; while (e.MoveNext()); return result; } } return default_rv; } public static T LastOrDefault(this IEnumerable source, Func predicate, T default_rv) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); T rv = default_rv; foreach (T element in source) if (predicate(element)) rv = element; return rv; } public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate) => LastOrDefault(source, select, predicate, default); public static TResult LastOrDefault(this IEnumerable source, Func select, Func predicate, TResult default_rv) { if (source == null) throw new ArgumentNullException(nameof(source)); if (select == null) throw new ArgumentNullException(nameof(select)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); TResult rv = default; foreach (T element in source) { TResult r = select(element); if (predicate(r)) rv = r; } return rv; } /// /// Simply returns enumerable.ToList(), under the guise ofo IReadOnlyList<> /// public static IReadOnlyList ToReadOnlyList(this IEnumerable enumerable) => enumerable.ToList(); public static Dictionary ToDictionary(this IEnumerable> key_values) => key_values.ToDictionary(kv => kv.Key, kv => kv.Value); public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector) => new ReadOnlyDictionary(enumerable.ToDictionary(key_selector)); public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, IEqualityComparer comparer) => new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, comparer)); public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector) => new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector)); public static ReadOnlyDictionary ToReadOnlyDictionary(this IEnumerable enumerable, Func key_selector, Func element_selector, IEqualityComparer comparer) => new ReadOnlyDictionary(enumerable.ToDictionary(key_selector, element_selector, comparer)); #region Min public static T Min(this IEnumerable enumerable, Func select_value) where T : IComparable => Min(enumerable, select_value, default(T)); public static T Min(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; T min = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (val.CompareTo(min) == -1) min = val; } return min; } public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison) => Min(enumerable, select_value, comparison, default); public static T Min(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; T min = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (comparison(val, min) == -1) min = val; } return min; } #endregion #region MinElement public static TElement MinElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MinElement(enumerable, select_value, default(TElement)); public static TElement MinElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; TElement min_el = etr.Current; T min = select_value(min_el); while (etr.MoveNext()) { T val = select_value(etr.Current); if (val.CompareTo(min) == -1) { min_el = etr.Current; min = val; } } return min_el; } public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => MinElement(enumerable, select_value, comparison, default); public static TElement MinElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; TElement min_el = etr.Current; T min = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (comparison(val, min) == -1) { min_el = etr.Current; min = val; } } return min_el; } #endregion #region Max public static T Max(this IEnumerable enumerable, Func select_value) where T : IComparable => Max(enumerable, select_value, default(T)); public static T Max(this IEnumerable enumerable, Func select_value, T return_if_empty) where T : IComparable { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; T max = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (val.CompareTo(max) == 1) max = val; } return max; } public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison) => Max(enumerable, select_value, comparison, default); public static T Max(this IEnumerable enumerable, Func select_value, Comparison comparison, T return_if_empty) { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; T max = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (comparison(val, max) == 1) max = val; } return max; } #endregion #region MaxElement public static TElement MaxElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MaxElement(enumerable, select_value, default(TElement)); public static TElement MaxElement(this IEnumerable enumerable, Func select_value, TElement return_if_empty) where T : IComparable { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; TElement max_el = etr.Current; T max = select_value(max_el); while (etr.MoveNext()) { T val = select_value(etr.Current); if (val.CompareTo(max) == 1) { max_el = etr.Current; max = val; } } return max_el; } public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison) => MaxElement(enumerable, select_value, comparison, default); public static TElement MaxElement(this IEnumerable enumerable, Func select_value, Comparison comparison, TElement return_if_empty) { var etr = enumerable.GetEnumerator(); if (!etr.MoveNext()) return return_if_empty; TElement max_el = etr.Current; T max = select_value(etr.Current); while (etr.MoveNext()) { T val = select_value(etr.Current); if (comparison(val, max) == 1) { max_el = etr.Current; max = val; } } return max_el; } #endregion #region Sum public static uint Sum(this IEnumerable enumerable, Func select) => Sum(enumerable.Select(select)); public static uint Sum(this IEnumerable enumerable) { uint sum = 0; foreach (uint val in enumerable) sum += val; return sum; } #endregion public static void DisposeAll(this IEnumerable source) { foreach (IDisposable d in source) d.Dispose(); } } public static class CollectionExtensions { #region AddRange public static void AddRange(this ICollection collection, params T[] items) { foreach (T item in items) collection.Add(item); } public static void AddRange(this ICollection collection, IEnumerable items) { foreach (T item in items) collection.Add(item); } #endregion public static void SetItems(this ICollection collection, IEnumerable items) { collection.Clear(); collection.AddRange(items); } } public static class DictionaryExtensions { #region TryGetValue public static bool TryGetValue(this Dictionary>> target, K k1, VK1 k2, VK2 k3, out V value) { if (target.TryGetValue(k1, out Dictionary> d1) && d1.TryGetValue(k2, out Dictionary d2)) return d2.TryGetValue(k3, out value); value = default; return false; } public static bool TryGetValue(this IDictionary target, K k1, VK k2, out V value) where VKD : IDictionary { if (target.TryGetValue(k1, out VKD d)) return d.TryGetValue(k2, out value); value = default; return false; } #endregion public static void AddOrUpdate(this IDictionary dictionary, TKey key, Func add_value_factory, Action update_value) { if (!dictionary.TryGetValue(key, out TValue value)) dictionary.Add(key, add_value_factory(key)); else update_value(key, value); } public static void AddOrUpdate(this IDictionary dictionary, TKey key, Func add_value_factory, Func update_value) { if (!dictionary.TryGetValue(key, out TValue value)) dictionary.Add(key, add_value_factory(key)); dictionary[key] = update_value(key, value); } public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func add_value_factory) { if (!dictionary.TryGetValue(key, out TValue value)) dictionary.Add(key, value = add_value_factory(key)); return value; } public static void SetValue(this IDictionary target, K k1, VK k2, V value) where VKD : IDictionary { if (!target.TryGetValue(k1, out VKD d)) target.Add(k1, d = Activator.CreateInstance()); d[k2] = value; } public static IReadOnlyDictionary Join(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target) => Join(dictionary, merge_target, (v1, v2) => (v1, v2)); public static IReadOnlyDictionary Join(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target, Func select) { var iks = dictionary.Keys.Intersect(merge_target.Keys); return new ReadOnlyDictionary(iks.ToDictionary(k => k, k => select(dictionary[k], merge_target[k]))); } public static IReadOnlyDictionary LeftJoin(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target, Func select, Func select_left_only) => dictionary.ToDictionary(kv => kv.Key, kv => { if (merge_target.TryGetValue(kv.Key, out TValue2 v2)) return select(kv.Value, v2); else return select_left_only(kv.Value); }); public static IReadOnlyDictionary SuperJoin(this IReadOnlyDictionary dictionary, IReadOnlyDictionary merge_target) { var eks1 = dictionary.Keys.Except(merge_target.Keys); var eks2 = merge_target.Keys.Except(dictionary.Keys); var iks = dictionary.Keys.Intersect(merge_target.Keys); return new ReadOnlyDictionary(eks1 .Select(k => (k, dictionary[k], default(TValue2))) .Concat(eks2.Select(k => (k, default(TValue1), merge_target[k]))) .Concat(iks.Select(k => (k, dictionary[k], merge_target[k]))) .ToDictionary(vals => vals.k, vals => (vals.Item2, vals.Item3)) ); } } public static class ListExtensions { #region InserSorted public static void InsertSorted(this IList list, T item) => list.InsertSorted(item, Comparer.Default); public static void InsertSorted(this IList list, T item, IComparer comparer) { for (int i = 0; i < list.Count; i++) if (comparer.Compare(list[i], item) > 0) { list.Insert(i, item); return; } list.Add(item); } #endregion #region Pop public static T Pop(this IList list, int index) { T rv = list.ElementAt(index); list.RemoveAt(index); return rv; } public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { for(int i = 0; i < list.Count; i++) { if (key_selector(list[i]).Equals(key)) { result = list[i]; return true; } } result = default(T); return false; } #endregion public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { if (list.Pop(key, key_selector, out T result)) { result.Dispose(); return true; } return false; } } } namespace System.Collections.ObjectModel { public static class ObservableCollectionExtensions { public static int RemoveAll(this ObservableCollection collection, Func match) { if (collection == null) return 0; // In terms of allocations we could do this more efficiently by copying items from the end of the // collection in (see https://referencesource.microsoft.com/#q=RemoveAll) but that would allow // transient duplication in the list which could be observed from the outside // Better to generate Remove events rather than move+delete events var to_remove = collection.Where(match).ToList(); foreach (var item in to_remove) { collection.Remove(item); } return to_remove.Count; } public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, NotifyCollectionChangedEventArgs e) => ReflectChange(target, source, create_item, null, e); public static void ReflectChange(this ObservableCollection target, IEnumerable source, Func create_item, Action item_destroyed, NotifyCollectionChangedEventArgs e) { try { switch (e.Action) { case NotifyCollectionChangedAction.Add: int i = e.NewStartingIndex; foreach (TData d in e.NewItems) { T item = create_item(d); target.Insert(i++, item); } break; case NotifyCollectionChangedAction.Move: target.Move(e.OldStartingIndex, e.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: for (int x = 0; x < e.OldItems.Count; x++) { T item = target[e.OldStartingIndex]; target.RemoveAt(e.OldStartingIndex); item_destroyed?.Invoke(item); } break; case NotifyCollectionChangedAction.Replace: i = e.NewStartingIndex; foreach (TData d in e.NewItems) { T old_item = target[i]; target[i++] = create_item(d); item_destroyed?.Invoke(old_item); } break; case NotifyCollectionChangedAction.Reset: var old_views = target.ToArray(); target.Clear(); if (item_destroyed != null) foreach (T item in old_views) item_destroyed(item); foreach (TData d in source) target.Add(create_item(d)); break; } }catch (Exception ex) { if (ex == null) { } } } public static IObservable> ObserveSelf(this ObservableCollection collection) => Observable.FromEvent(cb => (s, e) => cb(e), h => collection.CollectionChanged += h, h => collection.CollectionChanged -= h).Select(_ => collection); public static IObservable> ObserveSelf(this ObservableCollection collection, bool start_with_current) { var src = ObserveSelf(collection); return start_with_current? src.StartWith(collection) : src; } } } namespace mbts.collections.extensions { public static class HashSetExtensions { public static void sync_with(this HashSet set, IEnumerable values) { set.RemoveWhere(v => !values.Contains(v)); var adds = values.Distinct().Except(set).ToList(); foreach (var a in adds) set.Add(a); } } public static class ListExtensions { #region RemoveWhere public static void RemoveWhere(this IList list, Func where) { foreach (var r in list.Where(where).ToList()) list.Remove(r); } public static void RemoveWhere(this IList list, Func where, Action on_remove) { int count = list.Count; for (int i = 0; i < count; i++) { var t = list[i]; if (where(t)) { list.RemoveAt(i--); --count; on_remove(t); } } } private static Random rng = new Random(); public static void Shuffle(this IList list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } #endregion } public static class DictionaryExtensions { #region GetValueOrDefault public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key) => dictionary.TryGetValue(key, out TValue result) ? result : default; public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) => dictionary.TryGetValue(key, out TValue result) ? result : default; public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, TValue default_value) => dictionary.TryGetValue(key, out TValue result) ? result : default_value; public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key, Func default_factory) => dictionary.TryGetValue(key, out TValue result) ? result : default_factory(key); #endregion public static void AddOrUpdate(this IDictionary dictionary, TKey key, Action update_existing, Func create_new) { if (dictionary.TryGetValue(key, out TValue curr)) update_existing(curr); else dictionary.Add(key, create_new()); } // this overload prevents 'ambiguous calls' compilation errors due to Dictionary implementing IDictionary, and IReadOnlyDictionary. public static void sync_with(this IDictionary dictionary, Dictionary source, Func selector) => _sync_with(dictionary, source, selector); public static void sync_with(this IDictionary dictionary, IDictionary source, Func selector) => _sync_with(dictionary, source, selector); public static void sync_with(this IDictionary dictionary, IReadOnlyDictionary source, Func selector) => _sync_with_ro(dictionary, source, selector); static void _sync_with(this IDictionary dictionary, IDictionary source, Func selector) { var removes = dictionary.Keys.Except(source.Keys).ToList(); foreach (var k in removes) dictionary.Remove(k); var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); foreach (var kv in adds) dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); } static void _sync_with_ro(this IDictionary dictionary, IReadOnlyDictionary source, Func selector) { var removes = dictionary.Keys.Except(source.Keys).ToList(); foreach (var k in removes) dictionary.Remove(k); var adds = source.Except(dictionary.Keys, kv => kv.Key).ToList(); foreach (var kv in adds) dictionary.Add(kv.Key, selector(kv.Key, kv.Value)); } } }