[英]How to retrieve the values from list using indexes by linq query?
I have a list of int that contains 5,6,7,8,5,4,3. 我有一个包含5、6、7、8、5、4、3的int列表。 I like to retrieve the value from list using their index.
我喜欢使用它们的索引从列表中检索值。 For example, I give start index as 1 and end index 4 I will get 6,7,8,5 in new list.
例如,我将开始索引设为1,将结束索引设为4,我将在新列表中得到6,7,8,5。 How can I do this in Linq?
如何在Linq中做到这一点?
Use Skip
and Take : 使用
Skip
并获取 :
var results = list.Skip(1).Take(4);
EDIT: Note that it's not clear from your question exactly what limits you're using. 编辑:请注意,从您的问题尚不清楚您正在使用什么限制。 If you're trying to be inclusive on both ends, using 0-based indexing, you want:
如果您试图使用基于0的索引在两端实现包容性,则需要:
var results = list.Skip(startIndex).Take(endIndex - startIndex + 1);
Note that this won't let you get 0 results though - you may want to make endIndex
exclusive so that if it equals startIndex
, you get nothing. 请注意,这不会让您得到0个结果-您可能希望使
endIndex
互斥,以便如果它等于startIndex
,那么您什么也不会得到。 Then the code is: 然后代码是:
var results = list.Skip(startIndex).Take(endIndex - startIndex);
Or an alternative approach is to use them the other way round. 或者另一种方法是反过来使用它们。 For example, the last snippet above is equivalent to:
例如,上面的最后一个片段等效于:
var results = list.Take(endIndex).Skip(startIndex);
这可能为您工作:
list.Where((l, index) => index >= 1 && index <= 4 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.