partial void LabsBetweenTreatments_PreprocessQuery(int?TreatmentId, ref IQueryable <SpecificLabs> query) { var treatment = Treatments.Where(a => a.Id == TreatmentId).Single(); //look for the next treatment var nextTreatment = Treatments.Where(b => b.DateTreated > treatment.DateTreated).OrderBy(a => a.DateTreated).FirstOrDefault(); //if there is a treatment, get all labs between the two if (nextTreatment != null) { query = from lab in query where lab.DateLabIssued >= treatment.DateTreated && lab.DateLabIssued <= nextTreatment.DateTreated select lab; } //else just get the rest of the labs starting from that treatment else { query = from lab in query where lab.DateLabIssued >= treatment.DateTreated select lab; } }