我试图建立一个典型的网上商店,到目前为止已经解决了所有问题,但我遇到了以下问题:如何将List中的重复数据库值替换为数量,并将它们列入ListView?< / strong>例如如果我将两个相同的产品添加到我的购物车中,我希望能够显示数量,而不是在购物车列表中显示两个相同的产品。
PS:我在ListView中列出我的结果。
(购物车的Form_Load):
using (eShopEntities db = new eShopEntities()){
var list = new List<Product>(db.Products.ToList());
var listFilter = new List<Product>();
foreach (var id in list)
{
foreach (var Sessions in SessionData)//got selected products stored in sessions
{
if (id.ID == Sessions)
{
listFilter.Add(id); //Add all selected products(via session)
}
}
}
int TotSum = 0;
foreach (var sum in listFilter)
{
TotSum = TotSum + sum.Price;
}
cartListView.DataSource = listFilter; cartListView.DataBind();
lblSum.Text = TotSum.ToString();
}
现在,所有内容都列在aspx中。但我不确定如何从listFilter中替换重复数量 AND 将quanties-data和listFilter的结果一起发送到cartListWiev togheter。
我的产品表(SQL):ID(PK),名称,ImagePath,价格和CatergoryID(FK)
由于
答案 0 :(得分:1)
作为一种可能性(不是强制性的最好的,但从技术上说它应该起作用),你可以改变你的代码:
using (eShopEntities db = new eShopEntities()){
IDictionary<long, int> productQuantities = new Dictionary<long, int>(); // supposed your product.ID is of type long
var list = new List<Product>(db.Products.ToList());
var listFilter = new List<Product>();
foreach (var id in list)
{
foreach (var Sessions in SessionData)//got selected products stored in sessions
{
if (id.ID == Sessions)
{
if (!productQuantities.ContainsKey(id.ID)) // new
{
listFilter.Add(id); //Add all selected products(via session)
productQuantities.Add(id.ID, 1)
} // new else {
productQuantities[id.ID]++; // new
}
}
}
}
int TotSum = 0;
foreach (var sum in listFilter)
{
// TotSum = TotSum + sum.Price; // old
sum.Quantity = productQuantities[id.ID]; // supposed your class Product has corresponding property for quantities
TotSum = TotSum + sum.Price * sum.Quantity;
}
cartListView.DataSource = listFilter; cartListView.DataBind();
lblSum.Text = TotSum.ToString();
}