【问题标题】:Specific row withing a DataTable数据表中的特定行
【发布时间】:2012-12-11 11:47:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net linq datatable


    【解决方案1】:

    你可以这样做

    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
    

    【讨论】:

      【解决方案2】:

      你没有使用 linq。 DataTable 内置了此类操作的方法:

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

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

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

      【讨论】:

        猜你喜欢
        • 2016-12-13
        • 1970-01-01
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多