1

Was following tutorial here https://www.tutorialspoint.com/chash-linq-sum-method to Sum up values in a list. But I have multiple columns so code fails at:

            double res = ProductList.AsQueryable().Sum();
            Console.WriteLine(res);

see end of the file here https://dotnetfiddle.net/vmtTuP for issue.

2 Answers2

2

In a simple case, if you want to Sum some value, say, Qty, just specify it:

  double res = ProductList.Sum(item => item.Qty); 

If you want to sum several values (say, both Qty and Tax) in one go you can use Aggregate:

  (double Qty, double Tax) res = ProductList
    .Aggregate((Qty : 0.0, Tax : 0.0), (s, a) => (s.Qty + a.Qty, s.Tax + a.Tax)); 

  Console.Write($"Qty = {res.Qty}; Tax = {res.Tax}");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You don't need AsQueryable() and all you need to do is specify the field of your object you wish to sum - for example if you wanted to sum Tax:

double res = ProductList.Sum(x => x.Tax);
Console.WriteLine(res);
Jamiec
  • 133,658
  • 13
  • 134
  • 193