From c8cd2ae1ade67392f1ecccb869308e42cbb9ea7e Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sat, 9 Mar 2019 19:18:10 -0600 Subject: [PATCH] fix 'sync_with_never_duplicate()' - should remove items from 'dest' that aren't in 'src' --- .../spark/core/Utility/CollectionHelper.cs | 35 ++++++++++++------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/client/spark/core/Utility/CollectionHelper.cs b/src/client/spark/core/Utility/CollectionHelper.cs index 9778c41d0..1a29f939b 100644 --- a/src/client/spark/core/Utility/CollectionHelper.cs +++ b/src/client/spark/core/Utility/CollectionHelper.cs @@ -90,20 +90,25 @@ namespace mbts.utils { } // Note: this is not optimized, be wary of use with large collections - public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src) => + public static void sync_with_never_duplicate(IList dest, IEnumerable src) => sync_with_never_duplicate(dest, src, EqualityComparer.Default); // Note: this is not optimized, be wary of use with large collections - public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src, IEqualityComparer comp) { - int i = 0; - foreach (var val in src.empty_if_null()) { - int curr_index = dest.IndexOf(val); + public static void sync_with_never_duplicate(IList dest, IEnumerable src, IEqualityComparer comp) { + var src_list = src as IList ?? new List(src); + var src_set = src as ISet ?? new HashSet(src_list); + for (int i = 0; i < dest.Count; i++) { + if (!src_set.Contains(dest[i])) + dest.RemoveAt(i); + } + for (int i = 0; i < src_list.Count; i++) { + int curr_index = dest.IndexOf(src_list[i]); if (curr_index == i) { continue; - } else if (curr_index > 0 && curr_index < dest.Count) { + } else if (curr_index >= 0 && curr_index < dest.Count) { dest.RemoveAt(curr_index); } - dest.Insert(i++, val); + dest.Insert(i, src_list[i]); } } @@ -112,11 +117,16 @@ namespace mbts.utils { // Note: this is not optimized, be wary of use with large collections public static void sync_with_never_duplicate(ObservableCollection dest, IEnumerable src, Func create, Func key_selector, Func src_key_selector, IEqualityComparer key_comparer) { - int i = 0; - var src_map = src.ToDictionary(src_key_selector); + var src_list = src as IList ?? new List(src); + var src_map = src_list.ToDictionary(src_key_selector); + for (int i = 0; i < dest.Count; i++) { + var k = key_selector(dest[i]); + if (!src_map.ContainsKey(k)) + dest.RemoveAt(i); + } var dest_map = dest.ToDictionary(key_selector); - foreach (var val in src.empty_if_null()) { - TKey key = src_key_selector(val); + for (int i = 0; i < src_list.Count; i++) { + TKey key = src_key_selector(src_list[i]); if (dest_map.TryGetValue(key, out T dval)) { int curr_index = dest.IndexOf(dval); if (curr_index != i) { @@ -124,9 +134,8 @@ namespace mbts.utils { dest.Insert(i, dval); } } else { - dest.Insert(i, create(val)); + dest.Insert(i, create(src_list[i])); } - ++i; } }