【问题标题】:Get total of a data row asp.net获取数据行的总和 asp.net
【发布时间】:2012-11-18 18:50:33
【问题描述】:

我试图从单行中的每一列中获取值以等于总数。这是我在 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();

        }

有什么想法吗?我尝试调用每一列并添加它们,但这似乎不起作用。

【问题讨论】:

    标签: asp.net datatable dataset


    【解决方案1】:

    以旧的DataTable.Compute 方法为例:

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

    这是“现代”Linq 方法:

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

    编辑:似乎您想将每行的数值加到一个“总计”列中。然后你可以使用 Column-Expression:

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

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多