Answered by:
What does this line mean?

Question
-
User-2121520658 posted
Hi
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
Thank you
Wednesday, June 3, 2015 4:01 AM
Answers
-
User1577371250 posted
Hi,
var product = products.FirstOrDefault((p) => p.Id == id);
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();
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 3, 2015 4:59 AM -
User2024324573 posted
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.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 3, 2015 6:27 AM
All replies
-
User1577371250 posted
Hi,
var product = products.FirstOrDefault((p) => p.Id == id);
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();
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 3, 2015 4:59 AM -
User2024324573 posted
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.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 3, 2015 6:27 AM