Explanation of Code : retrieve item from Array using FirstorDefault()
.net, arrays, c#, linq
Solution
`FirstOrDefault(predicate)` iterates over collection and returns first element that matches the predicate. In your example it will be the first element with `p.Id == id`. When there is no value that matched the predicate default value is returned (`null` for all referece types).
`(p) => p.Id == id` is a lambda expression that matches `Func<Product, bool>` - it takes one parameter of type `Product` (it's named `p`) and returns `bool` value.
`FirstOrDefault` probably looks really similar to it's eduLINQ equivalent:
public static TSource FirstOrDefault<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
// Argument validation elided
foreach (TSource item in source)
{
if (predicate(item))
{
return item;
}
}
return default(TSource);
}
Problem
Lets say I have some items in an array ``` 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 } }; ``` Then lets say I try to retrieve using this method ``` public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; } ``` I have read what it does but I don't get what is happening here: ``` FirstorDefault(p => p.Id == id); ```