说明代码:使用FirstorDefault()
问题描述:
可以说我有一个数组说明代码:使用FirstorDefault()
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);
答
FirstOrDefault(predicate)
遍历集合,并返回该谓词匹配第一个元素。在你的例子中,它将成为p.Id == id
的第一个元素。当没有匹配谓词的值时,将返回默认值(所有引用类型均为null
)。
(p) => p.Id == id
是lambda expression匹配Func<Product, bool>
- 它需要Product
类型(它的命名p
)的一个参数和返回值bool
。
FirstOrDefault
可能看起来很相似,它是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);
}
答
这个条件比需要满足田间。
(p) => p.Id == id
是lambda表达式,它给出参数p回报p.Id == ID
这就是所谓的每一个元素,直到它是真实的。
因此,product
将是其中的Id给定id或零相匹配的第一个元素,如果不存在这样
参见:http://msdn.microsoft.com/en-us/library/vstudio/bb311046.aspx – 2013-04-08 07:41:37
它创建一个临时变量类型的产品,然后比较其'Id'属性与给定值 – Sandy 2013-04-08 07:41:41
这是一个lambda表达式,[检查它](http://msdn.microsoft.com/en-gb/library/bb397687.aspx) – fbstj 2013-04-08 07:41:48