我有一个包含一些列的表格。这是表的类
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public string Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
我需要找到表中 Datatype = 2 的最后一条记录,并为其找到差异 23:59 - CurDateTime。
为了区别,我写了属性
这是代码
[NotMapped]
public TimeSpan? LastStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 23, 59, 00);
var difference = midnight - CurDateTime;
return difference;
}
return null;
}
}
对于第一个元素,我编写了这样的代码
public JsonResult GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
var firstitem = ctx.Loggings.Where(x => x.Datatype == 1).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff
}).FirstOrDefault();
return Json(firstitem, JsonRequestBehavior.AllowGet);
}
}
但是我如何找到Datatype == 2
的最后一个元素?
最佳答案
你可以使用这个: 使用 LastOrDefault 并选择数据类型 == 2 的项目
public JsonResult GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
var lastItem = ctx.Loggings.LastOrDefault(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.LastStartDifference?.TotalMinutes ?? -1) * x.coeff
});
return Json(lastItem, JsonRequestBehavior.AllowGet);
}
}
关于c# - 获取表中特定数据的最后一个条目(ASP.NET MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904392/