我认为这将是微不足道的,但我不知道该怎么做.我有一个 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模板网!
车牌检测有哪些好的算法?What are good algorithms for vehicle license plate detection?(车牌检测有哪些好的算法?)
Unity中图像的onClick事件onClick event for Image in Unity(Unity中图像的onClick事件)
运行总 C#Running Total C#(运行总 C#)
单击带有 JAvascript.ASP.NET C# 的超链接时删除目录Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(单击带有 JAvascript.ASP.NET C# 的超链接时删除目录)
asp.net listview 在单击时突出显示行asp.net listview highlight row on click(asp.net listview 在单击时突出显示行)
从函数调用按钮 OnClickCalling A Button OnClick from a function(从函数调用按钮 OnClick)