首页 > 解决方案 > 更快地在 linq 中记录 n 条记录

问题描述

请看这个查询

return ContextDb.TestTbl.AsNoTracking().Where(x =>
                x.Field1 == newsPaperGroupId).OrderByDescending(x => x.ShowDateTime).Take(count).ToList();

是获取所有记录然后获取n条记录吗?

有没有更快的方法来做这个查询?

标签: c#performancelinqtake

解决方案


LINQ 使用延迟执行,这意味着它不会立即检索结果 - 直到您调用某些方法,如ToList()Single()Count()或使用循环遍历查询foreach等。

如果您的查询看起来像这样,那么它实际上会在考虑之前抓取所有记录。Field1 == newsPaperGroupIdcount

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);

但你所拥有的看起来不错。在您应用过滤器并限制要检索的记录数之前,它不会检索实际数据。


推荐阅读