我在我的web api项目上工作,我使用实体框架6.我需要编写LinqToEntity以按最新日期和unitId来检索行。
例如:
这是我的表:
Id|UnitId | NumberP | DateMeasure
1|14 |num1 |2008-01-20 13:10:22.000
2|32 |num2 |2010-05-20 13:11:38.000
3|48 |num3 |2011-08-20 13:10:18.000
4|85 |num4 |2015-11-20 14:10:22.000
5|14 |num5 |2010-05-20 13:11:38.000
6|32 |num6 |2010-05-20 13:12:38.000
7|85 |num7 |2014-11-20 17:20:32.000
以下是我需要使用LinqToEntity从表中获取的记录:
Id|UnitId | NumberP | DateMeasure
3|48 |num3 |2011-08-20 13:10:18.000
4|85 |num4 |2015-11-20 14:10:22.000
5|14 |num5 |2010-05-20 13:11:38.000
6|32 |num2 |2010-05-20 13:12:38.000
这是我试过的:
var t2 = from s in unitOfWork.SensorsMeasure.GetAll()
group s by s.SensorUnitId into g
select new
{
};
我分组之后如何按日期订购?
如何创建LinqToEntity查询以获得所需的结果?
答案 0 :(得分:1)
您可以使用let clause获取您感兴趣的每个组的元素:
var t2 = from s in unitOfWork.SensorsMeasure.GetAll()
group s by s.SensorUnitId into g
let latest = g.OrderByDescending(s => s.DateMeasure).FirstOrDefault()
select new
{
UnitId = g.Key,
NumberP = latest.NumberP,
DateMeasure = latest.DateMeasure
};