Get total of a data row asp.net

2019-08-29 10:15发布

问题:

Im trying to get the values from each column in a single row to equal a total. Here is the code that im using to achieve this in c# asp.net

DataTable dt = ds.Tables.Add("InspireTable");
        string pass = (String)Session["name"];
        if (pass.Equals("High"))
        {
            dt.Columns.Add("Inspire", typeof(string));
            dt.Columns.Add("SNS", typeof(int));
            dt.Columns.Add("TT", typeof(int));
            dt.Columns.Add("Music", typeof(int));
            dt.Columns.Add("Total", typeof(string));


            DataRow row = dt.NewRow();
            row["Inspire"] = "Score";
            row["SNS"] = 10;
            row["TT"] = 10;
            row["Music"] = 0;

            dt.Rows.Add(row);
            Chart1.DataSource = dt;
            this.GridView1.Visible = true;
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

Any ideas? I have tried calling each column and adding them but that seem not to work.

回答1:

With the old DataTable.Compute method, for example:

int snsTotal = (int) dt.Compute("SUM(SNS)", null); // the second argument is the filter

Here's the "modern" Linq approach:

int snsTotal = dt.AsEnumerable().Sum(r => r.Field<int>("SNS"));

Edit: it seems as if you want to sum the numeric values of each row into a "total"-column. Then you can use a Column-Expression:

dt.Columns.Add("Total", typeof(int), "SNS + TT + Music");