问题描述
我认为这将是微不足道的,但我不知道该怎么做.我有一个 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 的总和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!