I have a DataTable which has 5 columns:
The DataTable contains 5 rows.
this.LabelControl.Text = datatable.AsEnumerable()
.Sum(x => x.Field<int>("Amount"))
.ToString();
If you want to filter the results:
this.LabelControl.Text = datatable.AsEnumerable()
.Where(y => y.Field<string>("SomeCol") != "foo")
.Sum(x => x.Field<int>("MyColumn") )
.ToString();
You Can use Linq by Name Grouping
var allEntries = from r in dt.AsEnumerable()
select r["Amount"];
using name space using System.Linq;
You can find the sample total,subtotal,grand total in datatable using c# at Myblog
I think this solves
using System.Linq;
(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
If you have a ADO.Net DataTable you could do
int sum = 0;
foreach(DataRow dr in dataTable.Rows)
{
sum += Convert.ToInt32(dr["Amount"]);
}
If you want to query the database table, you could use
Select Sum(Amount) From DataTable
Try this
int sum = 0;
foreach (DataRow dr in dt.Rows)
{
dynamic value = dr[index].ToString();
if (!string.IsNullOrEmpty(value))
{
sum += Convert.ToInt32(value);
}
}
Compute Sum of Column in Datatable , Works 100%
lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();
if you want to have any conditions, use it like this
lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();