c# - 更快地在 linq 中记录 n 条记录
问题描述
请看这个查询
return ContextDb.TestTbl.AsNoTracking().Where(x =>
x.Field1 == newsPaperGroupId).OrderByDescending(x => x.ShowDateTime).Take(count).ToList();
是获取所有记录然后获取n条记录吗?
有没有更快的方法来做这个查询?
解决方案
LINQ 使用延迟执行,这意味着它不会立即检索结果 - 直到您调用某些方法,如ToList()
、Single()
、Count()
或使用循环遍历查询foreach
等。
如果您的查询看起来像这样,那么它实际上会在考虑之前抓取所有记录。Field1 == newsPaperGroupId
count
return ContextDb.TestTbl.AsNoTracking()
.Where(x => x.Field1 == newsPaperGroupId)
.OrderByDescending(x => x.ShowDateTime)
.ToList()
.Take(count);
如果它看起来像这样,那么它会在应用过滤器或限制记录的数量之前抓取TestTbl
(哎哟)中的所有内容。
return ContextDb.TestTbl.AsNoTracking()
.ToList()
.Where(x => x.Field1 == newsPaperGroupId)
.OrderByDescending(x => x.ShowDateTime)
.Take(count);
但你所拥有的看起来不错。在您应用过滤器并限制要检索的记录数之前,它不会检索实际数据。
推荐阅读
- sqlite - 在 Android 内部存储上使用 Sqlite
- c# - Asp.net (MVC) 身份验证 cookie 在重定向时丢失 - 但仅在 Firefox 上
- node.js - 使用 Node.js AWS Lambda 从 application/octet-stream MIME 中提取并保存 application/gzip
- javascript - 合并两个对象数组并将数组名称添加为属性
- kubernetes - 如何在创建时强制命名空间中的所有 pod 用标签 key=value 标记
- swift - 按下按钮时调用 nil 函数
- visual-studio - 在 Visual Studio 2017 中启动调试器时,如何自动运行我的 Vue 项目?
- azure - 通过专用网络连接 Azure MariaDB
- java - org.openqa.selenium.WebDriverException: java.net.ConnectException: 无法使用 GeckoDriver Firefox 和 Selenium 连接到 localhost/0:0:0:0:0:0:0
- apache-spark - 创建一个具有另一列最大值的新列