C# Method that loops list and access different Properties at different times

Viewed 68

So I have a List<Product> that I need to loop and calculate some stuff. Every Product has propery Price and Tax. What I want to do is to have a method where I can loop throught the list and calculate the total price and the total tax, but I don't want to write to methods for this.

At the moment I have this:

private double calculateTotalPrice()
        {
            List<Product> temp = this.GetList();
            double price = 0;
            for(int i = 0; i < Count; i++)
            {
                price += temp[i].Price;
            }

            return price;
        }

But with this method I need to have one method for calculating Price and another for Tax. Is it possible to change this method so that I can call it and at one moment calculate the Price, and next time I call it to calculate Tax? My hope is to do this without using If-statements but I'm not sure if this is possible.

Appreciate any help.

EDIT: Spelling

2 Answers

You can use an existing Sum method from System.Linq namespace without writing it by yourself

double price = temp.Sum(item => item.Price);
double tax = temp.Sum(item => item.Tax);

You can make use of the Aggregate LINQ extension method like below.

var totalPrice = temp.Aggregate((p1, p2) => p1.Price + p2.Price);
var totalTax = temp.Aggregate((t1, t2) => t1.Tax + t2.Tax);
Related