Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 944
CodingIntrigue Avatar asked Sep 27 '13 13:09

CodingIntrigue


People also ask

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What does .ANY mean in C#?

The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned. Let us see an example. int[] arr = {5, 7, 10, 12, 15, 18, 20};

How do you use take and skip in Linq?

The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

Which Linq method returns a Boolean value?

In LINQ, quantifier operators are used to returning a boolean value which shows that whether some or all elements satisfies the given condition.


1 Answers

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.

like image 190
Jeroen van Langen Avatar answered Sep 18 '22 16:09

Jeroen van Langen