Related to this: Adding new items dynamically to IQueryable hard-coded fake repository
How could I build the method for the following class, which would remove items from the list based on the value of one of its fields?
public class FakeProductsRepository
{
private readonly List<Product> fakeProducts = new List<Product>
{
new Product { ProductID = "xxx", Description = "xxx", Price = 1000 },
new Product { ProductID = "yyy", Description = "xxx", Price = 2000 },
new Product { ProductID = "zzz", Description = "xxx", Price = 3000 },
};
public void AddProduct(string productID, string description, int price)
{
fakeProducts.Add(new Product
{
ProductID = productID,
Description = description,
Price = price,
});
}
public void RemoveProduct(string productID)
{
????????
//How to remove the item from the fakeProducts List where ProductID == productID?
}
public IQueryable<Product> Products
{
get { return fakeProducts.AsQueryable(); }
}
}
The problem method is pointed out with “???????” and the comment string.
In general, for a collection I’d use this code:
Don’t forget the
ToList(), or you can get anInvalidOperationExceptionsaying “Collection was modified”.Update (thanks to linuxuser27):
But
List<T>also has a special method, takingPredicate<T>: