LINQ - Is Where(Predicate).FirstOrDefault() the same as FirstOrDefault(Predicate)

Bar*_*SIH 5 linq

I have always written my LINQ queries with the predicate in the Where clause followed by the FirstOrDefault clause. I started seeing examples with the predicate in the FirstOrDefault clause.

Is one better than the other? Would the answer be different with EF (SQL)?

A. Using Where Clause

List<Product> products = GetProductList(); 

Product productWhere = products.Where(p => p.ProductID == 789).FirstOrDefault(); 
Run Code Online (Sandbox Code Playgroud)

B. No Where Clause

List<Product> products = GetProductList(); 

Product productNoWhere = products.FirstOrDefault(p => p.ProductID == 789); 
Run Code Online (Sandbox Code Playgroud)

https://code.msdn.microsoft.com/LINQ-Element-Operators-0f3f12ce

Rob*_*vey 2

由于 Linq 中的方法链是延迟计算的,因此两者之间不应该有任何实质性差异。 Where.FirstOrDefault当它获得一个值时就会停止执行,就像FirstOrDefault(Predicate)意志一样。

换句话说,FirstOrDefault(或者任何其他下游的 Linq 运算符)一次接受一个项目进行Where评估,而不是一次接受整个列表(返回 an 的 Linq 运算符的结果本质上IEnumerable是一个yield return)。

另请参见
Where.FirstOrDefault 与 FirstOrDefault