Reputation: 8474
Is it possible using LINQ expression to skip some elements from the middle of the sequence? I want to Take N elements, then Skip M elements, then take the rest of the sequence. I know that I can write my own function for that but I wonder is it possible to do it using only built-in functions?
Upvotes: 4
Views: 1022
Reputation: 551
This can be done with Skip()
and Take()
, you just have to use Concat()
as well.
sequence.Take(N).Concat(sequence.Skip(N + M));
Upvotes: 2
Reputation: 8894
One way is to use the index:
sequence.Select((value, index) => new {value, index})
.Where(x => x.index < startOfRange || x.index > endOfRange)
.Select(x.value);
Or, even simpler: (can't believe I didn't think of that the first time)
sequence.Where((value, index) => index < startOfRange || index > endOfRange)
Upvotes: 5
Reputation: 35646
int n = 5;
int m = 10;
int k = n+m;
var seq = Enumerable.Range(100, 20).Where((p,i) => i<=n || i>= k)));
// the output is 100,101,102,103,104,105,115,116,117,118,119
Upvotes: 2