5
\$\begingroup\$

I have a LINQ 2 SQL query that needs to run a subquery in the where clause. The subquery just returns the largest date (from a date column) that is less than or equal to another date (an input to the function).

I originally had it like this (not this in the where clause of an outer query):

skew.CalibrationDate.Date == (from skew2 in db.Skew 
 where skew2.CalibrationDate.Date <= date.Date 
 select skew2.CalibrationDate).Max()

And then simplified it to:

skew.CalibrationDate.Date == db.Skew.Select(s => s.CalibrationDate.Date)
 .Where(s => s <= date.Date)
 .Max()

(note that the db.Skew table/object has multiple columns/properties but I'm only interested in the CalibrationDate for this clause and also that date is an input to the function that this is in, a regular DateTime variable).

Is it necessary for me to have all three of the Select(), Where() and Max() calls or is there some redundancy here? Could I put a lambda expression in the Max() call to get rid of one of the others?

asked Dec 2, 2015 at 9:16
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Is this what you are looking for?

skew.CalibrationDate.Date == db.Skew
 .Where(s => s.CalibrationDate.Date <= date.Date)
 .Max(s => s.CalibrationDate.Date)

Max will return the maximum value itself, not the object with the maximum date.

answered Dec 2, 2015 at 9:44
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.