34

我想从列表中获取值的总和。

例如:我在列表中有 4 个值 1 2 3 4 我想对这些值求和并将其显示在标签中

代码:

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);
        }
    }
}

有任何想法吗?提前致谢

4

4 回答 4

82

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));
于 2013-09-16T09:38:48.900 回答
17

使用总和()

 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)));

印刷:

10

于 2013-09-16T09:40:21.990 回答
8

You can use LINQ for this

var list = new List<int>();
var sum = list.Sum();

and for a List of strings like Roy Dictus said you have to convert

list.Sum(str => Convert.ToInt32(str));
于 2013-09-16T09:38:24.807 回答
2

这个怎么样?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
于 2013-09-16T09:44:36.780 回答