首页 > 解决方案 > 如何在单个 LinQ 查询中编写 OrderByDescending 和 where 子句

问题描述

我想显示UpdateDevice特定的最新值DeviceId。使用OrderByDescendingand编写 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

标签: c#linq

解决方案


您需要为谓词加上括号,即 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;

推荐阅读