diff --git a/Lawo.EmberPlusSharp/Model/MatrixBase`1.cs b/Lawo.EmberPlusSharp/Model/MatrixBase`1.cs index 70703bb8..2a0a98ae 100644 --- a/Lawo.EmberPlusSharp/Model/MatrixBase`1.cs +++ b/Lawo.EmberPlusSharp/Model/MatrixBase`1.cs @@ -326,15 +326,15 @@ private static int GetMaximumTotalConnects(MatrixType type, int targetCount, int private static void Insert(ObservableCollection existingSources, int[] sources, bool replace) { Array.Sort(sources); - int index = 0; - foreach (var source in sources) + if (replace) { - int? existingSource = null; + // Remove all elements in existingSources not contained in sources + var index = 0; - while ((index < existingSources.Count) && ((existingSource = existingSources[index]) < source)) + while (index < existingSources.Count) { - if (replace) + if (Array.BinarySearch(sources, existingSources[index]) < 0) { existingSources.RemoveAt(index); } @@ -343,13 +343,24 @@ private static void Insert(ObservableCollection existingSources, int[] sour ++index; } } + } + + // Insert sources elements into existingSources, but skip elements already present in existingSources + var insertIndex = 0; + + foreach (var source in sources) + { + int? existingSource = null; - if (existingSource != source) + while ((insertIndex < existingSources.Count) && ((existingSource = existingSources[insertIndex]) < source)) { - existingSources.Insert(index, source); + ++insertIndex; } - ++index; + if (source != existingSource) + { + existingSources.Insert(insertIndex, source); + } } }