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
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!
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};
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.
In LINQ, quantifier operators are used to returning a boolean value which shows that whether some or all elements satisfies the given condition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With