DataTable中的特定行

时间:2012-12-11 11:47:22

标签: asp.net linq datatable

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

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;
        }
    }

正如您所看到的,我的方法有效,但添加了我不想做的列。我该如何改变呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你没有拥有来使用linq。 DataTable具有用于此类操作的内置方法:

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

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

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