c# - 获取表中特定数据的最后一个条目(ASP.NET MVC)

标签 c# mysql asp.net asp.net-mvc entity-framework

我有一个包含一些列的表格。这是表的类

 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/

相关文章:

c# - 使用 SIP 中继、PBX 电话系统等

c# - 不从循环返回值

mysql - 如何在单个 SQL 查询中搜索列中的值并获取列的计数

javascript - Sequelize 。如何在创建中使用不同的参数值

asp.net - 当前的配置系统不支持用户范围的设置

c# - 目标数组不够长

c# - 如何使用 Windows 应用程序驱动程序/C# 从 TreeItem/DataItem 读取值?

mysql - Mysql 中的事件调度程序未运行

asp.net - 日期选择器 JavaScript

asp.net - 关于应用 CSS 时的 ASP.NET 页面呈现