更快地在 linq 中记录

faster take n record in linq

请查看此查询

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

是先fetch all record再取n条记录吗?

有没有更快的方法来执行此查询?

LINQ 使用 deferred execution,这意味着它不会立即检索结果 - 除非您调用某些方法,例如 ToList()Single()Count(),或使用 foreach 循环等遍历查询

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

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

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