Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count and sum total of DataTable with LINQ?

Tags:

c#

linq

I have a DataTable which has a column "amount" for each rows and I'd like to have the total sum of all the rows. And also, I'd like to get total number of rows in the DataTable. Could anyone teach me how to have it done with LINQ instead of ordinary way?

like image 324
Ye Myat Aung Avatar asked Dec 12 '22 05:12

Ye Myat Aung


1 Answers

Number of rows:

DataTable dt; // ... populate DataTable
var count = dt.Rows.Count;

Sum of the "amount" column:

DataTable dt; // ... populate DataTable
var sum = dt.AsEnumerable().Sum(dr => dr.Field<int>("amount"));
like image 110
Roy Goode Avatar answered Jan 07 '23 04:01

Roy Goode