c# - 如何从List中获取值的总和?

时间:2013-09-16 09:36:26

标签: c# asp.net

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

例如:我在列表中有4个值 1 2 3 4我想对这些值求和并在Label

中显示

代码:

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 个答案:

答案 0 :(得分:47)

您可以使用Sum函数,但您必须将字符串转换为整数,如下所示:

int total = monValues.Sum(x => Convert.ToInt32(x));

答案 1 :(得分:12)

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

打印:

  

10

答案 2 :(得分:6)

您可以将LINQ用于此

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

并且像Roy Dictus这样的字符串列表说你必须转换

list.Sum(str => Convert.ToInt32(str));

答案 3 :(得分:2)

这个怎么样?

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