简体   繁体   English

如何从序列中间剪切一些元素?

[英]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? 是否可以使用LINQ表达式跳过序列中间的某些元素? I want to Take N elements, then Skip M elements, then take the rest of the sequence. 我想要N个元素,然后跳过M个元素,然后取其余的序列。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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