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 从列表中选择提供的索引范围内的值
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
