C# List<int> 中 int 的总和范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10284133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum range of int's in List<int>
提问by Bali C
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.
我认为这将是微不足道的,但我不知道如何去做。我有一个List<int>,我想对一系列数字求和。
Say my list is:
说我的清单是:
var list = new List<int>()
{
1, 2, 3, 4
};
How would I get the sum of the first 3 objects? The result being 6. I tried using Enumerable.Rangebut couldn't get it to work, not sure if that's the best way of going about it.
我将如何获得前 3 个对象的总和?结果是 6。我尝试使用Enumerable.Range但无法让它工作,不确定这是否是最好的方法。
Without doing:
不做:
int sum = list[0] + list[1] + list[2];
采纳答案by James Hill
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:
如果要对从其他地方开始的范围求和,可以使用Skip:
var list = new List<int>()
{
1, 2, 3, 4
};
// 3 + 4
int sum = list.Skip(2).Take(2).Sum(); // Result: 7
Or, reorder your list using OrderByor OrderByDescendingand then sum:
或者,使用OrderBy或重新排序您的列表OrderByDescending,然后求和:
var list = new List<int>()
{
1, 2, 3, 4
};
// 3 + 4
int sum = list.OrderByDescending(x => x).Take(2).Sum(); // Result: 7
As you can see, there are a number of ways to accomplish this task (or related tasks). See Take, Sum, Skip, OrderBy& OrderByDescendingdocumentation for further information.
如您所见,有多种方法可以完成此任务(或相关任务)。有关详细信息,请参阅Take、Sum、和文档。SkipOrderByOrderByDescending
回答by David Young
Or just use Linq
或者只使用 Linq
int result = list.Sum();
To sum first three elements:
总结前三个要素:
int result = list.GetRange(0,3).Sum();

