Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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

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

like image 984
user2500094 Avatar asked Sep 16 '13 09:09

user2500094


4 Answers

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));
like image 191
Roy Dictus Avatar answered Oct 19 '22 19:10

Roy Dictus


Use 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

like image 27
DGibbs Avatar answered Oct 19 '22 18:10

DGibbs


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));
like image 9
makim Avatar answered Oct 19 '22 17:10

makim


How about this?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
like image 2
Prasad Kanaparthi Avatar answered Oct 19 '22 18:10

Prasad Kanaparthi