【问题标题】:Get single value using orderby clause in Linq [closed]在 Linq 中使用 orderby 子句获取单个值 [关闭]
【发布时间】:2013-12-18 11:28:46
【问题描述】:

您好,我是 LINQ 的新手,我想在 LINQ 中实现以下查询:

select top 1 Registrationid from registration order by datemodified desc

通过上述查询,我​​想返回最新更新的registrationid。

谁能告诉我上述查询的语法以写在LINQ

谢谢。

更新

var result = _dbcontext.Registrations.OrderByDescending(x => x.DateModified);

我尝试了更多语法,但最后上面似乎更适合我,但使用上面的语法我无法获得单个排序的 registrationid

【问题讨论】:

  • 这么急,你都没有时间去尝试实现它?
  • 我在过去 1 小时内尝试过这个,还在谷歌上搜索这就是为什么我在这里问谢尔盖先生
  • 我想我在我的问题一开始就补充说我是 LINQ 的新手
  • @Sergey:我已经用我的语法更新了我的问题。

标签: c# linq entity-framework


【解决方案1】:

你几乎做到了。只需添加FirstOrDefault 即可从数据库中选择TOP 1 实体。在您按日期对它们进行排序后,使用Select 进行项目结果:

var result = _dbcontext.Registrations
                       .OrderByDescending(x => x.DateModified)
                       .Select(x => x.RegistrationId) // select only id field
                       .FirstOrDefault(); // top 1

如果没有注册,此查询将返回最新的注册 ID,或默认值(0 表示整数)。

生成的 SQL 将如下所示:

SELECT TOP (1) 
[Extent1].[RegistrationId] AS [RegistrationId]
FROM [dbo].[Registrations] AS [Extent1]
ORDER BY [Extent1].[DateModified] DESC

【讨论】:

  • 但我认为上面的语法会给我们整行,我也写了同样的查询,但我无法获得registrationid。我只想返回registrationid。
  • @garvitgupta 抱歉,我以为你想要整个实体。我会更新答案
  • 没有问题,我在等
  • @garvitgupta 谢谢,已更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2018-08-21
  • 1970-01-01
  • 2023-03-08
  • 2018-03-23
  • 1970-01-01
相关资源
最近更新 更多