How to get the sum of List object property values using foreach
c#, foreach, list, oop
Solution
If you want to increment `PriceSum` variable with product price, use += operator:
foreach (var ProductsInCart in _cartList)
{
PriceSum += ProductsInCart.Price; // instead of =+
}
When you write `= +value` then its two separate operators = operator and + operator i.e. `+ProductsInCart.Price` just returns value of products, price, and then you assign this value to `PriceSum`. As result, you will have price of last product in list.
You also can use LINQ instead of this loop:
public float PriceAllContent
{
get { return _cartList.Sum(p => p.Price); }
}
Problem
What i'm trying to do Find the price sum for all items in a shoppingcart list. How i tried to solve it I think it makes sense to add it as a property in the Cart-class. I also think it would be logical to just use a foreach loop to iterate the CartList and add the itemprice (ProductsInCart.Price) to a temporary variable (PriceSum), which is returned in "Cart.PriceAllContent" property. C# ``` //Instantiating Cart Cart C2Cart = new Cart(); //Getting Item in cart from Session C2Cart.TakeCart(); //Writing out result Response.Write(C2Cart.PriceAllContent); ``` Classes ``` public class Cart { //FIELDS private List<ProductsInCart> _cartList; //PROPERTIES public List<ProductsInCart> CartList { get { return _cartList; } set { _cartList = value; } } public float PriceAllContent { get { float PriceSum= 0; foreach (var ProductsInCart in _cartList) { PriceSum= +ProductsInCart.Price; } return PriceSum; } } ........... } public class ProductsInCart { //FIELDS private int _id; private string _name; private float _price; private int _amount; ............ } ``` Complete class code can be seen here (may not be fully updated yet. Ask if needed) https://github.com/chmodder/PlanteskoleWebsite/tree/master/App_Code Problem Problem is, that when writing out the result, It would only write out the last items price instead of the sum of all itemprices. ``` Response.Write(C2Cart.PriceAllContent); ``` I allready tried searching for a solution, but couldn't find what i needed. If anyone can help me solve the problem i would be a happy man.