views:

71

answers:

2

There is a table in a SQL database like below :

SampleTable :

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

I wanna calculate total price like below :

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

Thus the Total Price would be 3100.

Now , I wanna calculate it with LINQ. e.g :

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

the upside code returns the wrong result !!! Could you please guide me ? Thanks.

+2  A: 

Try:

decimal TotalPrice = SampleTable.Sum(q => q.number * q.price);
Frédéric Hamidi
I've tested it before, It return an exception `Arithmetic overflow error converting expression to data type int.`
Mohammad
That's because you have sold a great deal of items ;) Try declaring `TotalPrice` as a `double` or a `decimal`. Answer updated accordingly.
Frédéric Hamidi
I tested `double`, but I receive the Exception again. I've done it with foreach.`var query = SampleTable.Select(q=>q); foreach (var item in query) TotalPrice += item.number * item.price` it doesn't return an exception !!!
Mohammad
`q.price` must be a `decimal` then. Try with `decimal TotalPrice`.
Frédéric Hamidi
No, It didn't fix :-(
Mohammad
+1  A: 

try this

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

      int totalPrice =  TotalPrice.Sum();
saurabh
Well, it's the same response like previous answer!!! what's the difference !!! in the other hand `SampleTable` is Enumerable by default.
Mohammad
Have you tries this or not ??? becoz this works for me
saurabh