'Splice IEnumerable with Linq

Is there an in-built way to splice an IEnumerable in Linq-To-Objects?

Something like:

List<string> options = new List<string>(); // Array of 20 strings
List<string> lastOptions = options.Splice(1, 5); // Gets me all strings 1 through 5 into a new list


Solution 1:[1]

Try:

List<string> options = new List<string>();
List<string> lastOptions = options.Skip(0).Take(5).ToList();

skip is used to show how to skip x elements (tnx drch)


You could create something like this: (extension method)

public static class SpliceExtension
{
    public static List<T> Splice<T>(this List<T> list, int offset, int count)
    {
        return list.Skip(offset).Take(count).ToList();
    }
}

But this will only be available to Lists.


You could also use it on IEnumerable<>

public static class SpliceExtension
{
    public static IEnumerable<T> Splice<T>(this IEnumerable<T> list, int offset, int count)
    {
        return list.Skip(offset).Take(count);
    }
}

This way the List isn't iterated completely.

use it like:

List<string> lastOptions = options.Splice(1, 5).ToList();

I like this way more, because it can be used on several linq queries.

Solution 2:[2]

There is no mentioning yet of the difference between JavaScript's slice and splice.

Note that splice also changes the original array in JavaScript whereas slice does not. The accepted answer is therefore a port of slice.

For completeness, here's a port of splice:

public static class SpliceExtension
{
    public static List<T> Splice<T>(this List<T> list, int start, int count)
    {
        var listWithDeletedElements = list.GetRange(start, count);
        list.RemoveRange(start, count);
        return listWithDeletedElements;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BenMorel
Solution 2