fix 'sync_with_never_duplicate()' - should remove items from 'dest' that aren't in 'src'

This commit is contained in:
John Colvin committed 2019-03-09 22:09:27 -06:00
1 parent 93afb5b602
commit c8cd2ae1ad
1 file changed
+22 -13
@@ -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<T>(ObservableCollection<T> dest, IEnumerable<T> src) =>
public static void sync_with_never_duplicate<T>(IList<T> dest, IEnumerable<T> src) =>
sync_with_never_duplicate(dest, src, EqualityComparer<T>.Default);
// Note: this is not optimized, be wary of use with large collections
public static void sync_with_never_duplicate<T>(ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> 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<T>(IList<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
var src_list = src as IList<T> ?? new List<T>(src);
var src_set = src as ISet<T> ?? new HashSet<T>(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<T, TSource, TKey>(ObservableCollection<T> dest, IEnumerable<TSource> src, Func<TSource, T> create, Func<T, TKey> key_selector, Func<TSource, TKey> src_key_selector, IEqualityComparer<TKey> key_comparer) {
int i = 0;
var src_map = src.ToDictionary(src_key_selector);
var src_list = src as IList<TSource> ?? new List<TSource>(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;
}
}