0

こんにちは、次の情報を持つカスタム BindingList Containing Products があります。

string ProductID
int Amount;

どうすれば次のことができるようになりますか。

ProductsList.Add(new Product("ID1", 10));
ProductsList.Add(new Product("ID2", 5));
ProductsList.Add(new Product("ID2", 2));

リストには2つの製品が含まれているはずです

ProductID = "ID1"   Amount = 10
ProductID = "ID2"   Amount = 7;

つまり、ショッピングカートのように機能します

私は、AddingNew イベントを見て、void InsertItem(int index, T item) をオーバーライドします

しかし、私は本当に始めるために少し助けが必要かもしれません

4

2 に答える 2

1

独自のコレクションを作成することが正しい選択になることはめったにありません。この場合、継承よりも包含を優先します。何かのようなもの

class ProductsList
{
    private readonly SortedDictionary<string, int> _products 
                                   = new Dictionary<string,int>();

    public void AddProduct(Product product)
    {
        int currentAmount;
        _products.TryGetValue(product.ProductId, out currentAmount);

        //if the product wasn't found, currentAmount will be 0
        _products[product.ProductId] = currentAmount + product.Amount;
    }
}

コメント:

  • (辞書ではなく)実際のIEnumerableが必要な場合は、KeyedCollectionを使用してください
  • 独自のクラスを作成する代わりに(必要なすべてのメソッドを実装する必要があります)、次のIEnumerable<Product>ような拡張メソッドを作成できますAddProduct-しかし、それは通常のメソッドを隠しAddませんか?それはもっと迅速で汚い方法だと思いますそれをすることの

IBindingList最後に、その部分について心配する必要はありません。いつでもBindingSourceを使用できます。

于 2010-11-17T19:12:29.737 に答える
1

.net ライブラリには多くの優れたコレクションがあるため、このカスタム リストが必要な理由はよくわかりませんが、以下のことを試してみました。

 public class ProductList
{
   public string ProductID {get;set;}
   public int Amount {get;set;}
}

public class MyBindingList<T>:BindingList<T> where T:ProductList
{

    protected override void InsertItem(int index, T item)
    {

        var tempList = Items.Where(x => x.ProductID == item.ProductID);
        if (tempList.Count() > 0)
        {
           T itemTemp = tempList.FirstOrDefault();
           itemTemp.Amount += item.Amount;


        }
        else
        {
            if (index > base.Items.Count)
            {
                base.InsertItem(index-1, item);
            }
            else
                base.InsertItem(index, item);

        }

    }

    public void InsertIntoMyList(int index, T item)
    {
        InsertItem(index, item);
    }



}

そして、このリストを使用できるクライアント コードで。

        ProductList tempList = new ProductList() { Amount = 10, ProductID = "1" };
        ProductList tempList1 = new ProductList() { Amount = 10, ProductID = "1" };
        ProductList tempList2 = new ProductList() { Amount = 10, ProductID = "2" };
        ProductList tempList3 = new ProductList() { Amount = 10, ProductID = "2" };

        MyBindingList<ProductList> mylist = new MyBindingList<ProductList>();

        mylist.InsertIntoMyList(0, tempList);
        mylist.InsertIntoMyList(1, tempList1);
        mylist.InsertIntoMyList(2, tempList2);
        mylist.InsertIntoMyList(3, tempList);
        mylist.InsertIntoMyList(4, tempList1);
        mylist.InsertIntoMyList(0, tempList3);
于 2010-11-17T14:58:56.923 に答える