How to select values within a provided index range from a List using LINQ(如何使用 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 从列表中选择提供的索引范围内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 LINQ 从列表中选择提供的索引范围内的值


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01