0

我有一个包含“总计”列的数据表。我希望能够获得特定行“总计”而不是所有行。

public void maxValue()
    {
        string pass = (String)Session["name"];
        DataTable table = (DataTable)Session["CocaCola"];
        int total = table.AsEnumerable().Sum(r => r.Field<int>("Total"));
        int totalAllowed = table.AsEnumerable().Sum(r => r.Field<Int32>("Total Allowed"));

        if (total >= totalAllowed)
        {
            Label1.Text = "Total value exceeded the maximum of " + totalAllowed;
        }
        else if (total < totalAllowed)
        {
            Label1.Text = "Total value which is allowed :" + totalAllowed;
        }
        if (pass.Equals("Low"))
        {
            Label1.Text = "You are not allowed any assets at this Stage";
            //SNS.Checked = false;
            //TT.Checked = false;
            //Music.Checked = false;
            //SNS.Enabled = false;
            //TT.Enabled = false;
            //Music.Enabled = false;
        }
    }

如您所见,我的方法有效,但添加了我不想做的列。我将如何改变它?

4

2 回答 2

0

您不必使用linq。DataTable 具有用于此类操作的内置方法:

var selectedTotal = table.Compute("sum(Total)", "columnX == 'x'");

这告诉表格计算具有指定值Total的行中所有单元格的总和。columnX

当然你可以使用 linq。Where()在计算总和之前,您需要添加 a 。

于 2012-12-11T15:11:36.980 回答
0

你可以这样做

int yourTargetindex = 0; //Change this to get the value of your target element
int total =(from row in table.AsEnumerable()
            select row.Field<int>("Total")).ElementAt(yourTargetindex);
  //This will return the first value of "total" in the DataTable
于 2012-12-11T12:56:21.527 回答