c# - 如何在单个 LinQ 查询中编写 OrderByDescending 和 where 子句
问题描述
我想显示UpdateDevice
特定的最新值DeviceId
。使用OrderByDescending
and编写 LinQ 查询时Where
,出现错误
无法执行文本选择:CS1061“int”不包含“OrderByDescending”的定义,并且找不到接受“int”类型的第一个参数的扩展方法“OrderByDescending”
数据类型
Id - int32
UpdatedDate- datetime
林奇
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()
or First()
,您可以阅读两者的区别:
var latestDate = Attendances.Where(a => a.Deviceid == 1)
.OrderByDescending(x=>x.Id)
.FirstOrDefault()
?.UpdatedDate;
推荐阅读
- unity3d - 无法统一检查 Cardboard XR 插件
- mysql - 是否有任何 shell 脚本可以在没有 TabLock 的情况下清理巨大的 activiti 历史数据库?
- javascript - 在 React 中访问 JSON 文件的数据
- jsgrid - 简单的editTemplate给出TypeError
- java - 为什么 Java 和 DB 时区会自动更改?
- python - 如何在登录 Power BI 时读取手机号码上发送的 otp。(必须避免多因素身份验证器)
- crystal-reports - Crystal Report 2016,使用没有汇总字段的中位数
- python - 在python中的类下敲击方法时,来自方法警告的功能即将到来
- python - Tkinter 与泡菜。Pyinstaller 可执行文件问题
- swift - 如何使 Text 具有与 Box 相同的位置和方向?