問題描述
Lambda 表達式中的 SQL WHERE 等價物是什麼? (What's the equivalence of an SQL WHERE in Lambda expressions?)
Here's what I have:
decimal sum = _myDB.Products.Sum(p => p.Price).GetValueOrDefault();
I also have two dates: DateTime start
, DateTime end
I want to retrieve the sum of all of the product prices between start and end, but I can't figure out how to incorporate the variables into the lambda equation.
How do you incorporate variables into a lambda equation to give it some specification?
參考解法
方法 1:
Use Enumerable.Where
decimal sum = _myDB.Products
.Where(p => (p.Date >= start) && (p.Date <= end) )
.Sum(p => p.Price)
.GetValueOrDefault();
方法 2:
decimal sum = _myDB.Products
.Where(p => p.Start >= mystartDate && p.End <= myenddate)
.Sum(p => p.Price)
Pardon my syntax. But, I hope you get the idea.
EDIT: Corrected after Reed's suggestion. Old code (incorrect)
decimal sum = _myDB.Products
.Sum(p => p.Price)
.Where(p => p.Start >= mystartDate && p.End <= myenddate)
方法 3:
_myDB.Products
.Where(p => p.start >= "somevalue")
.Where(p => p.end <= "somevalue")
.Sum(p => p.Price).GetValueOrDefault();
(by Matt、Reed Copsey、shahkalpesh、Rony)