2016-05-21 2 views
0

私は製品(クラス)のリストをメモリに持っており、各製品はサブ製品のリスト(空でもよい)を持つことができます。製品の在庫(特性)とすべての出現数を更新する方法はありますか?製品が販売だけでなく、他の製品にバンドルの一部として表示されている場合、あなたのツリーの深さはわずか1(サブ製品である場合はしたがって、たとえば、両方の数量は1階層アップデート

+0

ここでいくつかのコードと[.NETFiddle](http://dotnetfiddle.net/)のサンプルを共有できますか? – aloisdg

答えて

0

によって削減されます

サブ製品を持つことができません)、あなたは有名なSelectManyどの使用することができますIEnumerableをシーケンスの各要素を

プロジェクトを1つのシーケンスに 結果のシーケンスを平坦化します。任意の項目の量が束の変化に含まれる

List<Product> products = new List<Product>(); 

var allProductsWithSubs = (from p in products.SelectMany(x => x.SubProducts).Concat(products) 
          group p by p.ProductID into grp 
          select new 
          { 
           ProductID = grp.Key, 
           Quantity = grp.Sum(x => x.Quantity) 
          }).ToList(); 

public class Product 
{ 
    public int ProductID { set; get; } 
    public double Quantity { set; get; } 
    public List<Product> SubProducts { set; get; } 
} 
+0

あなたは 'ToList()'を必要としないかもしれません – aloisdg

+0

私は、既存のリストの中で製品数量を1減らす必要があります。 –

0

バンドル製品は、数量を毎回再計算することができます。更新はイベントを使用して実行できます。

class Product 
{ 
    public int Quantity 
    { 
     get { return _quantity}; 
     set 
     { 
      if (_quantity != value) 
      { 
       _quantity = value; 
       OnQuantityChanged(); 
      } 
     } 
    } 

    protected virtual void OnQuantityChanged() 
    { 
     var handler = QuantityChanged; 
     if (handler != null) handler(this, EventArgs.Empty); 
    } 

    int _quantity; 

    public event EventHandler QuantityChanged; 
} 

class BundleProduct: Product 
{ 
    public class BundleItem 
    { 
     public BundleItem(Product product, int requiredQuantity) 
     { 
      this.Product = product; 
      this.RequiredQuantity = requiredQuantity; 
     } 
     public int Quanity 
     { 
      get {return Product.Quantity/RequiredQuantity; } 
     } 

     public readonly Product Product; 
     public readonly int RequiredQuantity; 
    } 

    public IReadOnlyList<BundleItem> Items 
    { 
     get {return _items; 
    } 

    public void AddItem(Product product, int requiredQuantity) 
    { 
     var item = new BundleItem(product, requiredQuantity); 
     _items.Add(item); 
     product.QuantityChanged += ItemQuantityChanged; 
     RecaclulateQuantity(); 
    } 


    void RecalculateQuantity() 
    { 

     if (_updating) return false; 

     _updating = true; 
     try 
     { 
      // The quantity of a bundle is derived from 
      // availability of items it contains 
      int available = 0; 

      if (_items.Count != 0) 
      { 
       available = _items[0].Quantity; 
       for(int i = 1; i < _items.Count; ++i) 
       { 
        available = Math.Min(available, _items[i].Quanity); 
       } 
      } 
      this.Quantity = available; 
     } 
     finally 
     { 
      _updating = false; 
     } 
    }   

    void ItemQuantityChanged(object sender, EventArgs e) 
    { 
     RecalculateQuantity(); 
    } 

    bool _updating; 
    List<Product> _items; 

}