【发布时间】:2012-10-02 04:02:35
【问题描述】:
已经为此苦苦挣扎了一段时间。
我正在涉足 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;
}
任何帮助将不胜感激。
注意:可提供其他谷物
【问题讨论】:
-
@MarkByers 我确信这永远不会发生。
标签: c# asp.net asp.net-mvc lambda asp.net-web-api