如何将项目添加到列表中

我的项目中有模型。 这是模型的代码

public partial class Logging { public string Imei { get; set; } public DateTime CurDateTime { get; set; } public Nullable GPSDateTime2 { get; set; } public Nullable Latitude2 { get; set; } public Nullable Longitude2 { get; set; } public string Speed { get; set; } public Nullable Datatype { get; set; } public int Id { get; set; } [NotMapped] public TimeSpan? FirstStartDifference { get { if (CurDateTime != null) { var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00); var difference = CurDateTime - midnight; return difference; } return null; } } [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; } } [NotMapped] public int coeff = 2; } 

我需要从数据库中获取一些项目,这是第一个条目,其中Datatype==1和Last,其中Datatype ==2

所以我在后端编写这个方法

 public JsonResult GetStops() { using (var ctx = new GoogleMapTutorialEntities()) { var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select( x => new { lng = x.Longitude2, lat = x.Latitude2, difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff }).FirstOrDefault(); var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select( x => new { lng = x.Longitude2, lat = x.Latitude2, difference = (int)(x.LastStartDifference?.TotalMinutes ?? -1) * x.coeff }).LastOrDefault(); List items = new List {firstitem, lastItem}; return Json(firstitem, JsonRequestBehavior.AllowGet); } } 

在此之后,我需要将firstitemlastitem添加到列表中。

我把它写成List items = new List {firstitem, lastItem};

但是我收到了一个错误

严重级代码说明项目文件行抑制状态错误CS1950集合初始化程序的最佳重载添加方法“List.Add(Logging)”具有一些无效参数Heatmap C:\ Users \ nemes \ source \ repos \ Heatmap \ Heatmap \ Controllers \ HomeController .cs 37活动严重级代码说明项目文件行抑制状态错误CS1503参数1:无法从”转换为’Heatmap.Models.Logging’Heatmap C:\ Users \ nemes \ source \ repos \ Heatmap \ Heatmap \ Controllers \ HomeController。 cs 37有效

对于此List items = new List {firstitem, lastItem};

我如何将它们添加到List?

您将返回匿名类型而不是LoggingfirstitemlastItem是匿名类型 。 将您的代码更改为:

 x => new Logging { Longitude2 = x.Longitude2, Latitude2 = x.Latitude2, //And other properties } 

如果你仍然得到错误可能是因为你无法投影到映射的实体上,那么你需要从Logging实体创建一个具有所需属性的DTO类:

 public class LoggingDTO { public string Longitude2 { get; set; } public string Latitude2 { get; set; } //And other properties } 

然后:

 x => new LoggingDTO