我已经苦恼了一段时间。
我正在涉足WebAPI领域,我有一个列表,其中包含名称相同但价格不同的产品。我需要做的是在价格变化时删除产品的所有引用。
例如:
名称=“玉米片” 价格=“1.99M”
名称=“玉米片” 价格=“1.89M”
名称=“Rice Krispies” 价格=“2.09M”
名称=“玉米片” 价格=“2.09M”
没有 玉米片应该出现在我的最终列表中。
我已经写好了大部分内容,但是它们删除产品的时间过早,我不确定应该在哪里删除它们。
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;
}
任何帮助都将不胜感激。
注意:还有其他谷物可供选择。