如何从使用LINQ列表中选择一个提供的索引范围内的值 [英] How to select values within a provided index range from a List using LINQ
本文介绍了如何从使用LINQ列表中选择一个提供的索引范围内的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个LINQ新手试图用它来acheive以下内容:
I am a LINQ newbie trying to use it to acheive the following:
我有整数的列表: -
I have a list of ints:-
List<int> intList = new List<int>(new int[]{1,2,3,3,2,1});
现在,我想比较前三个元素的总和[索引范围0-2]与使用LINQ过去三年[索引范围3-5]。我尝试了LINQ选择和Take扩展方法还有的SelectMany方法,但我无法弄清楚如何这样说:
Now, I want to compare the sum of the first three elements [index range 0-2] with the last three [index range 3-5] using LINQ. I tried the LINQ Select and Take extension methods as well as the SelectMany method, but I cannot figure out how to say something like
(from p in intList
where p in Take contiguous elements of intList from index x to x+n
select p).sum()
我看着包含扩展方法太,但没有看到让我我想要的。有什么建议么?谢谢你。
I looked at the Contains extension method too, but that doesn't see to get me what I want. Any suggestions? Thanks.
推荐答案
使用的跳过然后拿。
yourEnumerable.Skip(4).Take(3).Select( x=>x )
(from p in intList.Skip(x).Take(n) select p).sum()
这篇关于如何从使用LINQ列表中选择一个提供的索引范围内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文