views:

315

answers:

3

Hi,

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?

+10  A: 

Use Enumerable.Where

decimal sum = _myDB.Products
                   .Where(p => (p.Date >= start) && (p.Date <= end) )
                   .Sum(p => p.Price)
                   .GetValueOrDefault();
Reed Copsey
Agreed in terms of implementation, but queries like this are a lot clearer on multiple lines. Line up the dots :)
Jon Skeet
Good point on the formatting - I just stuck with his original question's formatting method, for consistency, but this is how I typically write it in my own code.
Reed Copsey
@Jon: Done. Didn't see your comment until just now.
Jeff Yates
Good point Jon. There is always something to learn (even from comments). Haha :)
shahkalpesh
A: 
_myDB.Products
.Where(p => p.start >= "somevalue")
.Where(p => p.end <= "somevalue")
.Sum(p => p.Price).GetValueOrDefault();
Rony
There's no need to have two where clauses with separate predicates.
Matthew Flaschen
I prefer this style since it improves readability
Rony
+1  A: 
 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)
shahkalpesh
The Where clause needs to go before Sum. Sum returns a decimal, and you can't do ".Where" on a decimal value.
Reed Copsey
Guys, will this work differently (i.e different from WHERE and then SUM)?
shahkalpesh
This won't compile at all. You cannot run .Where on a single value, which is what's returned by Sum().
Reed Copsey
Ah. Sorry about that. I will correct it. Thanks Reed
shahkalpesh
No problem. When you're using a fluent interface like this, each method returns a new object. In the case of methods like Where(), it returns a new IEnumerable<T>, which is why you can "chain" them together. .Sum() just returns a single value (decimal), so you can't do another method that's expecting IEnumerable<T> after Sum()
Reed Copsey
+1 for clear explanation.
shahkalpesh