現在一直在掙扎。從列表中刪除所有項目<T>如果T發生變化
我正在將腳趾浸入WebAPI世界,我有一個列表可以包含具有相同名稱但價格不同的產品。我需要做的是刪除全部對產品的引用是價格發生變化。
例如。
名= 「玉米片」 價格= 「1.99M」
NAME = 「玉米片」 價格= 「1.89M」
NAME = 「脆米花」 價格= 「209萬」
NAME = 「玉米片」 價格=「 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我一直保證永遠不會發生。 – Brett