Terrible title, I know...
This works and gives me what I'm looking for, but I know there must be a better way to do it:
var query = (from a in DB
where a.Date.HasValue
select a).AsEnumerable();
double avg = (from a in query
select (a.Date.Value.Subtract(a.OtherDate).Days).Average();
Basically, a.Date is a nullable datetime, and I want to get the average of (a.Date - a.OtherDate) only when a.Date exists (or else the calculation wouldn't work).
Things like this won't work:
double avg = (from a in DB
where a.Date.HasValue
select a.Date.Value.Subtract(a.OtherDate).Days).Average();
I know I've seen similar problems where the solution was to explicitly set the nullable field to nullable datetime, making the Average method work. I haven't seen it where the nullable field was part of a calculation like this.
Thanks in advance.
Edit: To clear things up a bit, let me give you Ben's solution and the error message it generates. I have to admit I left another part out of it...a.OtherDate is actually a bit more tricky...let me illustrate:
var avg = DB.Where(a => a.Date.HasValue)
.Where(a => a.ForeignKeyReference.Date.HasValue)
.Select(a => a.Date.Value.Subtract(a.ForeignKeyReference.Date.Value).Days)
.Average();
...and the error:
InvalidOperationException: Could not translate expression 'Table(DB).Where(a => a.Date.HasValue).Where(a => a.ForeignKeyReference.Date.HasValue).Select(a => a.Date.Value.Subtract(a.ForeignKeyReference.Date.Value).Days).Average()' into SQL and could not treat it as a local expression.
Seems as though the "Subtract" method or "Days" property has no translation to SQL. My first example worked because the second query was LINQ to objects. Does anyone know if there's a way to write the LINQ query in a way that will translate to SQL?