[英]Method for removing items from List
与此相关: 将新项目动态添加到IQueryable硬编码的假存储库
我如何为下一个类构建方法,该方法将根据其一个字段的值从列表中删除项目?
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(); }
}
}
用“ ???????”指出问题的方法 和注释字符串。
通常,对于一个集合,我将使用以下代码:
var productsToRemove = fakeProducts.Where(p => p.ProductID == productID).ToList();
foreach(var product in productsToRemove)
{
fakeProducts.Remove(product);
}
不要忘了ToList()
,否则您会得到一个InvalidOperationException
写着“ Collection被修改”。
更新(感谢linuxuser27):但是List<T>
也有一个特殊的方法,采用Predicate<T>
:
fakeProducts.RemoveAll(product => product.ProductID == productID);
尝试将LINQ与where
子句一起使用 。 请注意,您需要.NET 3.5。
var reducedProducts = from r in fakeProducts
where r.ProductID != productID
select r;
这将使您的收藏减少。
您还可以使用RemoveAll()
方法,该方法采用谓词,但会修改当前集合。
fakeProducts.RemoveAll(delegate (Product r) { return r.ProductID != productID; });
如果按产品ID查找商品是常见的操作,请考虑将列表替换为以产品ID为键的字典。
但是,如果您希望将List保留为数据结构,则循环遍历它(假设只有一个具有给定ProductID的产品):
foreach(Product p in fakeProducts)
{
if(p.ProductId == productID)
{
fakeProducts.remove(p);
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.