Sum range of int#39;s in Listlt;intgt;(Listlt;intgt; 中 int 的总和范围)
问题描述
我认为这将是微不足道的,但我不知道该怎么做.我有一个 List<int>
,我想对一系列数字求和.
I reckon this will be quite trivial but I can't work out how to do it. I have a List<int>
and I want to sum a range of the numbers.
假设我的清单是:
var list = new List<int>()
{
1, 2, 3, 4
};
如何获得前 3 个对象的总和?结果是 6.我尝试使用 Enumerable.Range
但无法让它工作,不确定这是否是最好的方法.
How would I get the sum of the first 3 objects? The result being 6. I tried using Enumerable.Range
but couldn't get it to work, not sure if that's the best way of going about it.
不做:
int sum = list[0] + list[1] + list[2];
推荐答案
您可以使用 采取
&总和
:
You can accomplish this by using Take
& Sum
:
var list = new List<int>()
{
1, 2, 3, 4
};
// 1 + 2 + 3
int sum = list.Take(3).Sum(); // Result: 6
如果您想对从其他地方开始的范围求和,可以使用 跳过
:
If you want to sum a range beginning elsewhere, you can use Skip
:
var list = new List<int>()
{
1, 2, 3, 4
};
// 3 + 4
int sum = list.Skip(2).Take(2).Sum(); // Result: 7
或者,使用 OrderBy
重新排序您的列表a> 或 OrderByDescending
然后求和:
Or, reorder your list using OrderBy
or OrderByDescending
and then sum:
var list = new List<int>()
{
1, 2, 3, 4
};
// 3 + 4
int sum = list.OrderByDescending(x => x).Take(2).Sum(); // Result: 7
如您所见,有多种方法可以完成此任务(或相关任务).请参阅 Take
、Sum
, 跳过
, OrderBy
&OrderByDescending
文档了解更多信息.
As you can see, there are a number of ways to accomplish this task (or related tasks). See Take
, Sum
, Skip
, OrderBy
& OrderByDescending
documentation for further information.
这篇关于List<int> 中 int 的总和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:List<int> 中 int 的总和范围


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