简体   繁体   中英

How to cut some elements from the middle of the sequence?

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?

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)
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

这可以通过Skip()Take()来完成,你只需要使用Concat()

sequence.Take(N).Concat(sequence.Skip(N + M));
myList.Where((o, i) => i <= startSkip || i >= endSkip);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM