我真的不知道爲什麼你需要這個自定義列表,因爲.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);
什麼?請張貼一些代碼 – TalentTuner 2010-11-17 14:11:02
不多,真的沒有任何代碼呢。仍在尋找文檔 – gulbaek 2010-11-17 14:16:55
雖然我最好的選擇是保護覆蓋void InsertItem(int index,T item),如果它的新產品調用base.InsertItem(index,item);否則請更新 – gulbaek 2010-11-17 14:20:22