2012-12-11 33 views
0

我有一個數據表,其中有一個「總計」列。我希望能夠獲得特定的行「Total」而不是所有的行。使用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; 
     } 
    } 

正如你可以看到我的方法工作,但添加我不想做的列。我將如何去改變它?

回答

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 
0

你不使用LINQ。數據表已經內置方法這樣操作的:

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

這告訴表格來計算行的所有Total單元格的總和,其中columnX具有指定的值。

當然你可以使用linq。在計算總和之前,您需要添加一個Where()

相關問題