简体   繁体   English

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

[英]How to write OrderByDescending and where clause in single LinQ query

I want to show the latest UpdateDevice -value of a particular DeviceId . 我想显示特定DeviceId的最新UpdateDevice When writing a LinQ query using OrderByDescending and Where , I'm getting the error 使用OrderByDescendingWhere编写LinQ查询时,出现错误

Cannot execute text selection: CS1061 'int' does not contain a definition for 'OrderByDescending' and no extension method 'OrderByDescending' accepting a first argument of type 'int' could be found 无法执行文本选择:CS1061'int'不包含'OrderByDescending'的定义,并且找不到扩展方法'OrderByDescending'接受类型为'int'的第一个参数

Datatypes 资料类型

Id - int32
UpdatedDate- datetime

LinQ 临Q

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

You need to put parenthesis for you predicate ie where clause. 您需要为谓词即where子句添加括号。

Either use query syntax or lambda expression completely. 完全使用查询语法或lambda表达式。 The following should work: 以下应该工作:

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

or use lambda expression syntax: 或使用lambda表达式语法:

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

Side Note: 边注:

If single item is intended to be returned, then you can use FirstOrDefault() or First() , you can read about the difference of both : 如果要返回单个项目,则可以使用FirstOrDefault()First() ,以了解两者的区别:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM