C# LINQ-如何根据distinct列选择distinct记录
我已经创建了一个Web API,在其中我试图对所有给出日期时间范围的记录进行fetcC# LINQ-如何根据distinct列选择distinct记录,c#,linq,asp.net-web-api,C#,Linq,Asp.net Web Api,我已经创建了一个Web API,在其中我试图对所有给出日期时间范围的记录进行fetc public HttpResponseMessage GetMeterPing(DateTime start, DateTime end) { try { var startDateTime = start; var endDateTime = end; var result = medEntitites.tj_xhqd.Where(m =>
public HttpResponseMessage GetMeterPing(DateTime start, DateTime end)
{
try
{
var startDateTime = start;
var endDateTime = end;
var result = medEntitites.tj_xhqd.Where(m => m.sjsj <= startDateTime && m.sjsj >= endDateTime)
.OrderByDescending(o => o.sjsj)
.Select(s => new { s.zdjh, s.sjsj, s.xhqd })
.Distinct().ToList();
return Request.CreateResponse(HttpStatusCode.OK, new { data = result});
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
注意:zdjh
是仪表编号,sjsj
是仪表的ping日期时间,xhqd
是ping值
现在在上面的响应中,有多个相同的zdjh
值。我想设置我的LINQ
,使其返回单个zdjh
=>米数、最后一个sjsj
=>ping日期时间值和最后一个xhqd
=>ping值
如何设置LINQ?任何帮助都将不胜感激。这就是你想要实现的目标吗
medEntitites.tj_xhqd.OrderByDescending(x => x.zdjh).ThenByDescending(x => x.sjsj).ThenByDescending(x => x.xhqd).DistinctBy(x => x.zdjh).ToList();
通过。
zdjh
进行区分,然后从每组中选择具有最新的sjsj
和xhqd
的元素。m.sjsj=endDateTime
非常奇怪,我认为您这里有一个错误。如果endDateTime@Flater我确实想要在给定的日期时间之间获取记录,我下载了更多linq,但仍然无法使用DistinctBy
,则此值只能计算为true。在要使用DistinctBy的文件中,添加以下命名空间:using MoreLinq;。确保您已经使用NuGet安装了MoreLinq软件包。是的,这就是我所缺少的。
medEntitites.tj_xhqd.OrderByDescending(x => x.zdjh).ThenByDescending(x => x.sjsj).ThenByDescending(x => x.xhqd).DistinctBy(x => x.zdjh).ToList();