How to count and sum DataTable using LINQ?

I have a DataTable that has a “sum” column for each row, and I would like to have a total sum of all rows. And also, I would like to get the total number of rows in a DataTable. Can someone teach me how to do this with LINQ, and not the usual way?

+4
source share
4 answers

Number of lines:

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

Amount column "amount":

 DataTable dt; // ... populate DataTable var sum = dt.AsEnumerable().Sum(dr => dr.Field<int>("amount")); 
+8
source

The aggregate allows you to avoid listing the rows twice (you can get the number of rows from the collection of rows, but this is more to show how to extract multiple aggregates in 1 pass):

 var sumAndCount = table.AsEnumerable().Aggregate(new { Sum = 0d, Count = 0}, (data, row) => new { Sum = data.Sum + row.Field<double>("amount"), Count = data.Count + 1}); double sum = sumAndCount.Sum; int count = sumAndCount.Count; 
+2
source
 decimal[] Amount = {2,3,5 }; var sum = Amount.Sum(); var count = Amount.Count(); 
0
source

Based on Roy Hood Answer that you can also create an extension

  public static int Sum(this DataTable table, string Column) { return table.AsEnumerable().Sum(dr => dr.Field<int>(Column)); } 

Unfortunately, you cannot be more general because there is no where T : numeric

0
source

Source: https://habr.com/ru/post/1395189/


All Articles