| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Collections.ObjectModel; |
| | | 3 | | |
| | | 4 | | namespace SwitchBlade.Core |
| | | 5 | | { |
| | | 6 | | /// <summary> |
| | | 7 | | /// Synchronizes an <see cref="ObservableCollection{T}"/> with a source list in-place, |
| | | 8 | | /// preserving object identity and minimizing UI change notifications. |
| | | 9 | | /// Uses a two-pointer algorithm for O(N) complexity. |
| | | 10 | | /// </summary> |
| | | 11 | | public static class ObservableCollectionSync |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Synchronizes <paramref name="collection"/> to match <paramref name="source"/> |
| | | 15 | | /// while preserving existing object references and minimizing move/insert/remove operations. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <typeparam name="T">Element type.</typeparam> |
| | | 18 | | /// <param name="collection">The observable collection to sync (mutated in-place).</param> |
| | | 19 | | /// <param name="source">The authoritative source list defining the desired order and content.</param> |
| | | 20 | | public static void Sync<T>(ObservableCollection<T> collection, IList<T> source) |
| | 40 | 21 | | { |
| | | 22 | | // Phase 1: Remove items not in source |
| | 40 | 23 | | var sourceSet = new HashSet<T>(source); |
| | 146 | 24 | | for (int i = collection.Count - 1; i >= 0; i--) |
| | 34 | 25 | | { |
| | 34 | 26 | | if (!sourceSet.Contains(collection[i])) |
| | 10 | 27 | | collection.RemoveAt(i); |
| | 34 | 28 | | } |
| | | 29 | | |
| | | 30 | | // Phase 2: Two-pointer sync for ordering and insertion |
| | 39 | 31 | | int ptr = 0; |
| | 198 | 32 | | for (int i = 0; i < source.Count; i++) |
| | 60 | 33 | | { |
| | 60 | 34 | | var item = source[i]; |
| | 60 | 35 | | if (ptr < collection.Count && EqualityComparer<T>.Default.Equals(collection[ptr], item)) |
| | 19 | 36 | | { |
| | 19 | 37 | | ptr++; |
| | 19 | 38 | | } |
| | | 39 | | else |
| | 41 | 40 | | { |
| | 41 | 41 | | int foundAt = -1; |
| | 84 | 42 | | for (int j = ptr + 1; j < collection.Count; j++) |
| | 6 | 43 | | { |
| | 6 | 44 | | if (EqualityComparer<T>.Default.Equals(collection[j], item)) |
| | 5 | 45 | | { |
| | 5 | 46 | | foundAt = j; |
| | 5 | 47 | | break; |
| | | 48 | | } |
| | 1 | 49 | | } |
| | | 50 | | |
| | 41 | 51 | | if (foundAt != -1) |
| | 5 | 52 | | { |
| | 5 | 53 | | collection.Move(foundAt, ptr); |
| | 5 | 54 | | } |
| | | 55 | | else |
| | 36 | 56 | | { |
| | 36 | 57 | | collection.Insert(ptr, item); |
| | 36 | 58 | | } |
| | 41 | 59 | | ptr++; |
| | 41 | 60 | | } |
| | 60 | 61 | | } |
| | 39 | 62 | | } |
| | | 63 | | } |
| | | 64 | | } |