This question is the second part of another question of mine, but this time focused on LINQ-to-SQL.
I have 2 tables, one containing meter IDs, and another containing measurements for some of the meters in the first table. This is the table structure:
MeterConfig:
- MeterID (int)
- MeterNumber (char[16])
- Type (char[25])
Readings:
- MeterID (int)
- Date (datetime)
- Value (numeric(18,6))
I need to get the last reading (and its date) from a given period for each meter, as well as the meter number. The date a meter was last read can differ from one to the other. Some meters might not have any readings in that period; in that case, they must be ignored.
I managed to do this, but I'm not exactly thrilled by how I did it. Is there a more efficient way of doing it, without having to do almost the same subquery twice?
(from cfg in MeterConfigs
join r in Readings on cfg.MeterID equals r.MeterID
where
r.Date >= startDate && r.Date <= endDate
select new
{
Number = cfg.MeterNumber,
ReadingDate =
(
from r in Readings
where cfg.MeterID == r.MeterID && r.Date >= startDate && r.Date <= endDate
orderby r.Date descending
select r.Date
).Take(1),
Value =
(
from r in Readings
where cfg.MeterID == r.MeterID && r.Date >= startDate && r.Date <= endDate
orderby r.Date descending
select r.Value
).Take(1)
})
.GroupBy(x => x.Number)
.Select(x => x.First());