問題描述
我認為這將是微不足道的,但我不知道該怎么做.我有一個 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 的總和范圍的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!