Insert only if new else update in BindingList
Hi I have a custom BindingList Containing Products with the following information
string ProductID
int Amount;
How would I make it possible to do the following.
ProductsList.Add(new Product("ID1", 10));
ProductsList.Add(new Product("ID2", 5));
ProductsList.Add(new Product("ID2", 2));
The list should then contain 2 Products
ProductID = "ID1" Amount = 10
ProductID = "ID2" Amount = 7;
So It workes kind of like a Shopping Cart
Im looking at the AddingNew Event and override void InsertItem(int index, T item)
But I could really need a little he开发者_高级运维lp getting started
i really don't know why you require this custom list as there are many good collections in the .net library but i have tried something below.
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);
}
}
and in the client code where you can use this list.
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);
Creating your own collection is rarely the right choice - I would favor containment rather than inheritance in this case. Something like
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;
}
}
Comments:
- If you need an actual IEnumerable (as opposed to a dictionary), use a KeyedCollection
- Instead of creating your own class (which forces you to implement all the methods you want), you can write an extension method for
IEnumerable<Product>
, something likeAddProduct
- but that won't hide the regularAdd
method do I guess it's more of a quick and dirty way of doing it
Lastly, don't worry about the IBindingList
part - you can always use a BindingSource
精彩评论