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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:19:58  来源:igfitidea点击:

c# - How to get sum of the values from List?

c#asp.net

提问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 Sumfunction, 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

Use Sum()

使用Sum()

 List<string> foo = new List<string>();
 foo.Add("1");
 foo.Add("2");
 foo.Add("3");
 foo.Add("4");

 Console.Write(foo.Sum(x => Convert.ToInt32(x)));

Prints:

印刷:

10

10

回答by Prasad Kanaparthi

How about this?

这个怎么样?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();