4

假设我在数组中有一些项目

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);
4

2 回答 2

3

FirstOrDefault(predicate)遍历集合并返回与谓词匹配的第一个元素。在您的示例中,它将是第一个带有p.Id == id. 当没有与谓词匹配的值时,返回默认值(null对于所有引用类型)。

(p) => p.Id == id是一个匹配的lambda 表达式Func<Product, bool>- 它接受一个类型Product的参数(名为p)并返回bool值。

FirstOrDefault可能看起来非常类似于它的eduLINQ 等效项

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); 
}
于 2013-04-08T07:45:03.590 回答
1

这是需要满足的条件。

(p) => p.Id == id

是 lambda 函数,给定参数 p 返回 p.Id == id

它在每个元素上调用,直到它为真。

因此,product将是 Id 与给定 id 匹配的第一个元素,如果不存在则为 null

于 2013-04-08T07:42:44.103 回答