code_junkie

Datatable's Compute Function For Rows

Nov 12th, 2011
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. DataTable dt = WhateverCreatesDataTable();
  2. DataRow dr = dt.Rows[0];
  3. int sum = dt.Columns.Cast<DataColumn>().Sum(dc=>(int)dr[dc]);
  4.  
  5. DataTable dt = WhateverCreatesDataTable();
  6. DataRow dr = dt.Rows[0];
  7. int sum = 0;
  8.  
  9. foreach(DataColumn dc in dt.Columns)
  10. sum += (int)dr[dc];
  11.  
  12. DataColumn totalColumn = new DataColumn();
  13. totalColumn.DataType = System.Type.GetType("System.Int32");
  14. totalColumn.ColumnName = "Total";
  15. totalColumn.Expression = "Product1 + Product2 + Product3 + Product4 + Product5";
  16.  
  17. // Populate and get the DataTable dt then add this computed column to this table
  18.  
  19. dt.Columns.Add(totalColumn);
  20. //Now if you access the column "Total" of the table you will get the desired result.
Add Comment
Please, Sign In to add comment