I have a code here that tells you that, for every product in a bound list called product of a ProductListSource.DataSource
, I have an if statement that if the product.ProdID
is equal to the text you have inputted, you should add that on to a listbox. But the problem is I want a limiter... I don't want the same id to be added more than one. Here's my code demonstrating what I have done so far:
private void AddToCartButton_Click(object sender, EventArgs e)
{
foreach (var product in (BindingList<Product>) ProductListSource.DataSource)
{
if (product.ProdID == ProdIDText.Text.Trim())
{
CartList.Items.Add(product);
}
}
}
You can use the Distinct LINQ extension method to filter products with common product IDs:
var productList = (BindingList<Product>)ProductListSource.DataSource;
foreach (var product in productList.Distinct((one, two) => one.ProdID == two.ProdID))
{
if (product.ProdID == ProdIDText.Text.Trim())
{
CartList.Items.Add(product);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.