[英]I'm trying to find the subtotal of the selected items
I have the prices of the items in an array: 我有一个数组中的项目的价格:
double[] productPriceArray = { 1162.99, 399.99, 329.99, 199.99, 149.99 };
I am trying to find the total of the ones that a user puts in a "cart". 我试图找到用户放入“购物车”中的商品总数。 I'm not sure how to go about that.
我不确定该怎么做。 I know I can use the line of code:
我知道我可以使用以下代码行:
subtotal = productCostArray[lbxCart.SelectedIndex];
lblSubtotal.Text = subtotal.ToString("c");
to find the total of one of the indices, but how can I find the total of multiple indices? 查找一个索引的总数,但是如何找到多个索引的总数?
Thanks! 谢谢!
There is no way in the current design , You need atleast a list of product and product price mapping then you need a list of products in the cart and in the cart class you can define a function to get the subtotal of all products. 当前设计中没有办法,您需要至少一个产品列表和产品价格映射,然后在购物车中需要一个产品列表,并且在购物车类中可以定义一个函数来获取所有产品的小计。
public class Product
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public double Price { get; set; }
}
public class ShoppingCart
{
public string CartId { get; set; }
public List<Product> Products { get; set; }
public void AddProductToCart(Product p)
{
if(Products==null)
Products = new List<Product>();
if(p!=null)
Products.Add(p);
}
public double CartPrice()
{
return Products != null ? Products.Sum(p => p.Price):0D;
}
}
and usage 和用法
var shopCart = new ShoppingCart();
shopCart.AddProductToCart(new Product {ProductId = "1",Price = 12.09, ProductName = "P1"});
shopCart.AddProductToCart(new Product {ProductId = "2",Price = 11.09, ProductName = "P2"});
MessageBox.Show(shopCart.CartPrice().ToString());
如果您有一个选定项目索引的列表(如您的示例所示),则可以执行以下操作:
var subtotal = SelectedIndices.Select(idx => productPriceArray[idx]).Sum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.