ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

SkipFrom

Bypasses a specified number of elements in a sequence from a given start position

Source

static class Extensions {

    /// <summary>
    /// Bypasses a specified number of elements in a sequence from a given start position
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">An IEnumerable<T> to return elements from.</param>
    /// <param name="start">The number of elements to return before the elements are skipped.</param>
    /// <param name="count">The number of elements to skip before returning the remaining elements.</param>
    /// <returns></returns>
    public static IEnumerable<T> SkipFrom<T>(this IEnumerable<T> source, int start, int count) {
        int i = 0;
        foreach (var item in source) {
            if (i < start || i >= start + count) {
                yield return item;
            }
            i++;
        }
    }
}

Example

List<int> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var qry = data.SkipFrom(3, 4);

// Outputs: 1, 2, 3, 8, 9, 10
foreach (var item in qry) {
    Console.WriteLine(item);
}

Author: Fons Sonnemans

Submitted on: 26 apr 2024

Language: csharp

Type: ienumerable-t

Views: 196