diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -523,18 +523,51 @@ throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } - count += index; // Make `count` the upper bound. - - InOrderTreeWalk(node => - { - if (index >= count) - { - return false; + if (this is TreeSubSet) + { + T[] destination = array; + int destinationIndex = index; + int end = index + count; + InOrderTreeWalk(node => + { + if (destinationIndex >= end) + { + return false; + } + + destination[destinationIndex++] = node.Item; + return true; + }); + } + else if (count != 0 && root is Node start) + { + CopyInOrder(start, array, index, index + count); + } + } + + private static int CopyInOrder(Node? node, T[] array, int index, int end) + { + while (node != null) + { + if (node.Left is Node left) + { + index = CopyInOrder(left, array, index, end); + if (index == end) + { + break; + } } array[index++] = node.Item; - return true; - }); + if (index == end) + { + break; + } + + node = node.Right; + } + + return index; } void ICollection.CopyTo(Array array, int index) diff --git a/src/libraries/System.Collections/tests/Generic/SortedSet/SortedSet.Generic.cs b/src/libraries/System.Collections/tests/Generic/SortedSet/SortedSet.Generic.cs --- a/src/libraries/System.Collections/tests/Generic/SortedSet/SortedSet.Generic.cs +++ b/src/libraries/System.Collections/tests/Generic/SortedSet/SortedSet.Generic.cs @@ -27,6 +27,17 @@ } protected override bool DefaultValueAllowed => true; + + [Fact] + public void SortedSet_Generic_CopyTo_WithIndexAndPartialCount() + { + var set = (SortedSet)CreateSortedSet(new[] { 7, 3, 5, 1, 9 }, 5, 5); + int[] array = { -1, -1, -1, -1, -1 }; + + set.CopyTo(array, 1, 3); + + Assert.Equal(new[] { -1, 1, 3, 5, -1 }, array); + } [Fact] public void SortedSet_Generic_GetViewBetween_MinMax() # End of patch