Sum of rows of SQL table with LINQ?

There is a table in the SQL database:

SampleTable:

-----------------------
 id | number | price 
-----------------------
 1  |   3    | 300
 2  |   1    | 200
 3  |   5    | 100
 4  |   10   | 10
 5  |   30   | 30
 6  |   1    | 500
-----------------------

I want to calculate the total price as shown below:

in each row => var SumOfEachRow = number * price;
Total Price = sum of SumOfEachRow;

So there Total Pricewill be 3100.

Now I want to calculate it using LINQ. eg:

int TotalPrice = from q in SampleTable
                 select new
                 {
                    TotalPrice = q.number * q.price 
                 }.Sum();

the upper code returns the wrong result !!! Could you guide me? Thank.

+3
source share
2 answers

Try:

decimal TotalPrice = SampleTable.Sum(q => q.number * q.price);
+4
source

try it

  var TotalPrice = from q in SampleTable.AsEnumerable()
                         let y = Convert.ToInt32(q["number"]) * Convert.ToInt32(q["price"])
                         select y;

      int totalPrice =  TotalPrice.Sum();
+1
source

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


All Articles