Slice<T>(int start, int end)

public static IEnumerable<T> Slice<T>(this IEnumerable<T> collection, int start, int end)
{
    int index = 0;
    int count = 0;

    if (collection == null)
        throw new ArgumentNullException("collection");

    // Optimise item count for ICollection interfaces.
    if (collection is ICollection<T>)
        count = ((ICollection<T>)collection).Count;
    else if (collection is ICollection)
        count = ((ICollection)collection).Count;
    else
        count = collection.Count();

    // Get start/end indexes, negative numbers start at the end of the collection.
    if (start < 0)
        start += count;

    if (end < 0)
        end += count;

    foreach (var item in collection)
    {
        if (index >= end)
        yield break;

        if (index >= start)
        yield return item;

        ++index;
    }
}
Example:
char[] h = "0123456789abcdef".ToCharArray();

var a = h.Slice(0, 3);    // returns { 0, 1, 2 }
var b = h.Slice(4, 9);    // returns { 4, 5, 6, 7, 8 }
var c = h.Slice(10, 100); // returns { a, b, c, d, e, f }
var d = h.Slice(5, 5);    // returns { }
var e = h.Slice(-10, -5); // returns { 6, 7, 8, 9, a }

Description

Returns the range of elements between the specified start and end indexes. Negative numbers count from the end, rather than the start, of the sequence. Values of 'end' larger than the actual sequence are truncated and do not cause index-out-of-bounds exceptions. Functionally very similar to Python's list[x:y] slices.

Details

Double click on the code to select all.

 

;