HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Simplifying a LINQ expression that finds the largest date smaller than another date

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expressionlinqthethandatelargestthatfindssimplifyingsmaller

Problem

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?

Solution

Is this what you are looking for?

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


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

Code Snippets

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

Context

StackExchange Code Review Q#112552, answer score: 4

Revisions (0)

No revisions yet.