diff --git a/MoreLinq.Test/ExcludeTest.cs b/MoreLinq.Test/ExcludeTest.cs index fbe71da82..58ecd698c 100644 --- a/MoreLinq.Test/ExcludeTest.cs +++ b/MoreLinq.Test/ExcludeTest.cs @@ -1,3 +1,20 @@ +#region License and Terms +// MoreLINQ - Extensions to LINQ to Objects +// Copyright (c) 2008 Jonathan Skeet. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#endregion + namespace MoreLinq.Test { using NUnit.Framework; @@ -143,5 +160,14 @@ public void TestExcludeStartIndexGreaterThanSequenceLength() Assert.That(result, Is.EqualTo(sequence)); } + + [TestCase(new[] { 0, 1, 2, 3, 4, 5 }, 0, 6, ExpectedResult = new int[0])] + [TestCase(new[] { 0, 1, 2, 3, 4, 5 }, 2, 6, ExpectedResult = new[] { 0, 1 })] + [TestCase(new[] { 0, 1, 2, 3, 4, 5 }, 0, 3, ExpectedResult = new[] { 3, 4, 5 })] + [TestCase(new[] { 0, 1, 2, 3, 4, 5 }, 2, 3, ExpectedResult = new[] { 0, 1, 5 })] + public int[] TestExcludeOnKnownInput(int[] source, int startIndex, int count) + { + return source.AsTestingSequence().Exclude(startIndex, count).ToArray(); + } } } diff --git a/MoreLinq/Exclude.cs b/MoreLinq/Exclude.cs index ae65ca6a7..d016a04f1 100644 --- a/MoreLinq/Exclude.cs +++ b/MoreLinq/Exclude.cs @@ -43,18 +43,30 @@ public static IEnumerable Exclude(this IEnumerable sequence, int startI return _(); IEnumerable _() { - var index = -1; + var index = 0; var endIndex = startIndex + count; - var iter = sequence.GetEnumerator(); + using var iter = sequence.GetEnumerator(); + // yield the first part of the sequence - while (iter.MoveNext() && ++index < startIndex) + for (; index < startIndex; index++) + { + if (!iter.MoveNext()) + yield break; yield return iter.Current; + } + // skip the next part (up to count items) - while (++index < endIndex && iter.MoveNext()) - continue; + for (; index < endIndex; index++) + { + if (!iter.MoveNext()) + yield break; + } + // yield the remainder of the sequence while (iter.MoveNext()) + { yield return iter.Current; + } } } }