c# - 如何从列表中获取值的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18824761/
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
c# - How to get sum of the values from List?
提问by user2500094
I want to get sum of the values from list.
我想从列表中获取值的总和。
For example: I have 4 values in list 1 2 3 4 I want to sum these values and display it in Label
例如:我在列表 1 2 3 4 中有 4 个值我想对这些值求和并将其显示在标签中
Code:
代码:
protected void btnCalculate_Click(object sender, EventArgs e)
{
string monday;
TextBox txtMonTot;
List<string> monTotal = new List<string>();
if (Application["mondayValues"] != null)
{
List<string> monValues = Application["mondayValues"] as List<string>;
for (int i = 0; i <= gridActivity.Rows.Count - 1; i++)
{
GridViewRow row = gridActivity.Rows[i];
txtMonTot = (TextBox)row.FindControl("txtMon");
monday = monValues[i];
monTotal.Add(monday);
}
}
}
Any ideas? Thanks in advance
有任何想法吗?提前致谢
采纳答案by Roy Dictus
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
您可以使用该Sum
函数,但您必须将字符串转换为整数,如下所示:
int total = monValues.Sum(x => Convert.ToInt32(x));
回答by makim
You can use LINQ for this
您可以为此使用 LINQ
var list = new List<int>();
var sum = list.Sum();
and for a List of strings like Roy Dictus said you have to convert
对于像 Roy Dictus 这样的字符串列表说你必须转换
list.Sum(str => Convert.ToInt32(str));
回答by DGibbs
回答by Prasad Kanaparthi
How about this?
这个怎么样?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();