been struggling with this for a while now.
I’m dipping my toe in the WebAPI world and I have a List that can contains products with the same name but different prices. What I need to do is remove all references to a product is variations in price occur.
eg.
name = “Cornflakes” Price = “1.99M”
name = “Cornflakes” Price = “1.89M”
name = “Rice Krispies” Price = “2.09M”
name = “Cornflakes” Price = “2.09M”
No cornflakes should appear in my final list.
I’ve got the bulk written but it’s removing the products too soon and I’m unsure where I should be removing them.
public IEnumerable<Product> GetProductsByCategory(int Id)
{
List<Product> sourceProductList = products.Where(p => p.CategoryID == Id).ToList();
List<Product> tempProducts = new List<Product>();
List<Product> targetProductList = new List<Product>();
foreach (var product in sourceProductList)
{
bool isInTempList = tempProducts.Any(x => x.Name == product.Name);
if (!isInTempList)
{
tempProducts.Add(product);
}
else
{
Product tempProduct = product;
bool isPriceDifferent = tempProducts.Where(y => y.Name == tempProduct.Name).Any(y => y.Price != tempProduct.Price);
if (isPriceDifferent)
{
tempProducts.RemoveAll(p => p.Name == product.Name);
// too soon as I may have lots of products with the same name
// but need to remove based on product.Name
}
}
}
targetProductList.AddRange(tempProducts);
return targetProductList;
}
Any help would be greatly appreciated.
Note: other cereals are available
Please try this:
In the result you will have only one “Rice Krispies” item. I’m sure it will work faster than solution with GroupBy and Distinct, because we don’t need to do these unnecessary things in your case.
Working Code – http://ideone.com/X8A3v