如何使用 LINQ 从列表中选择提供的索引范围内的值 [英] How to select values within a provided index range from a List using LINQ

查看:43
本文介绍了如何使用 LINQ 从列表中选择提供的索引范围内的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个 LINQ 新手,试图用它来实现以下目标:

I am a LINQ newbie trying to use it to acheive the following:

我有一个整数列表:-

List<int> intList = new List<int>(new int[]{1,2,3,3,2,1});

现在,我想使用 LINQ 比较前三个元素 [索引范围 0-2] 与后三个 [索引范围 3-5] 的总和.我尝试了 LINQ Select 和 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()

我也查看了 Contains 扩展方法,但这并没有得到我想要的东西.有什么建议?谢谢.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆