[英]How to write OrderByDescending and where clause in single LinQ query
我想顯示特定DeviceId
的最新UpdateDevice
。 使用OrderByDescending
和Where
編寫LinQ查詢時,出現錯誤
無法執行文本選擇:CS1061'int'不包含'OrderByDescending'的定義,並且找不到擴展方法'OrderByDescending'接受類型為'int'的第一個參數
資料類型
Id - int32
UpdatedDate- datetime
臨Q
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.