Last post Jun 03, 2015 06:27 AM by mostafasydney
Jun 03, 2015 04:01 AM|msman|LINK
I am learning Web API. What does this mean? (please do not answer as it finds a product by its ID, I already know that, but I do not understand why it is written this way).
var product = products.FirstOrDefault((p) => p.Id == id);
This code is from : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
Jun 03, 2015 04:59 AM|Lokesh B R|LINK
1. It will find the product with the specified ID.
2. FirstOrDefault() will return the First Product from the products where Product.Id == id.
Suppose if the product with the ID is not found then NULL will be returned.
You can write as follows as well
var product = products.Where(p=> p.Id == id).FirstOrDefault();
Jun 03, 2015 06:27 AM|mostafasydney|LINK
It is LINQ expression, know more about it at : https://msdn.microsoft.com/en-us/library/bb397926.aspx
It replaces the SQL query that we used to write to work with database. With the evolution of LINQ and Entity Framework now it is easy to write queries within the code.
As Lokesh B R explained the expression, it will just return the product which will first match with the id parameter.