2013-03-20 52 views
0

我有項目的價格在陣列中的小計:我試圖找到所選項目

double[] productPriceArray = { 1162.99, 399.99, 329.99, 199.99, 149.99 }; 

我試圖找到總認爲用戶將在的那些的「大車」。我不知道該怎麼做。我知道我可以使用的代碼行:

subtotal = productCostArray[lbxCart.SelectedIndex]; 
lblSubtotal.Text = subtotal.ToString("c"); 

找到總的指標之一,但我怎麼能找到總多指數?

謝謝!

+0

請問你的「購物車」有一系列指數?如果是這樣,'for'循環可能是最簡單的。 – Matthew 2013-03-20 04:48:07

+0

你是什麼意思「多個指數的總和」 – 2013-03-20 04:48:22

回答

0

當前設計中沒有辦法,您至少需要產品和產品價格映射清單,然後您需要購物車中的產品清單和購物車類中的定義函數以獲得所有產品的小計產品。

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; 
    } 
} 

和使用

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()); 
0

如果您選擇項目的索引列表(如你的例子似乎暗示),你可以這樣做:

var subtotal = SelectedIndices.Select(idx => productPriceArray[idx]).Sum(); 
+0

如果兩種不同的產品具有相同的價格? – 2013-03-20 04:49:20

+0

好點。新的解決方案解決這個 – joce 2013-03-20 04:51:06