假设我在数组中有一些项目
Product[] myProducts = new Product[]
{
new Product { ID = 1, name = "Ketchup1", category = "Sauces", price = 200.00m },
new Product { ID = 2, name = "Ketchup2", category = "Sauces", price = 200.00m },
new Product { ID = 3, name = "Ketchup3", category = "Sauces", price = 200.00m }
};
然后假设我尝试使用这种方法检索
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
我已经阅读了它的作用,但我不明白这里发生了什么:
FirstorDefault(p => p.Id == id);