我真的不知道你为什么需要这个自定义列表,因为 .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);