If I use loops in the get of a property, does this mean every time I call get on the property, it executes the loop? For eg, below, if I call CartViewModel.Total, does this mean it executes the loop inside SubTotal and Discount?
public class CartViewModel
{
public decimal SubTotal { get { return CartViewItems.Sum(c => c.Price); } }
public decimal Discount { get { return CartViewItems.Sum(c => Total-SubTotal); } }
public decimal Total { get { return SubTotal-Discount; } }
public List<CartViewItem> CartViewItems { get; set; }
}
public class CartViewItem
{
public decimal Price { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public float DiscountPercent {get; set;}
public decimal SubTotal { get { return Price*Quantity; } }
public decimal Total
{
get
{
return Convert.ToDecimal(((float)Price * (1 - (DiscountPercent / 100))
* Quantity));
}
}
}
Is there a way to optimize this?
Yes, every time you call the property, it will execute the loop.
Properties are really just syntactic sugar over method calls. Very nice syntactic sugar, but only sugar.
You might want to change CartViewModel to avoid exposing the list directly - instead, keep the list private, give some appropriate methods to mutate it (e.g. Add and Clear methods), probably make it implement IEnumerable<CartViewItem> itself, and keep track of the subtotal and discount as the list is mutated. That's assuming that CartViewItem is immutable, of course...
Alternatively (as John suggested), just make it more obvious that you're actually doing work, changing the properties to ComputeTotal(), ComputeDiscount() and ComputeSubTotal() methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With