如何在单个LinQ查询中编写OrderByDescending和where子句



我想显示特定DeviceId的最新UpdateDevice值。当使用OrderByDescendingWhere编写LinQ查询时,我得到错误

无法执行文本选择:CS1061"int"不包含"OrderByDescending"的定义,没有扩展方法接受"int"类型的第一个参数的"OrderByDescending"可以是找到

数据类型

Id - int32
UpdatedDate- datetime

LinQ

from a in Attendances
where a.DeviceId == 1 
.OrderByDescending(x=>x.Id)
.Take(1)
select a.UpdatedDate

您需要为谓词插入括号,即where子句。

请完全使用查询语法或lambda表达式。以下内容应该有效:

(from a in Attendances
where a.Deviceid == 1 
select a)
.OrderByDescending(x=>x.Id)
.Take(1)
.Select(x=>x.UpdatedDate)

或使用lambda表达式语法:

Attendances.Where(a =>  a.Deviceid == 1) 
.OrderByDescending(x=>x.Id)
.Take(1)
.Select(a => a.UpdatedDate);

旁注:

如果要退回单个项目,则可以使用FirstOrDefault()First(),您可以阅读两者的区别:

var latestDate = Attendances.Where(a =>  a.Deviceid == 1) 
.OrderByDescending(x=>x.Id)
.FirstOrDefault()
?.UpdatedDate;

相关内容

  • 没有找到相关文章

最新更新