使用Linq获取记录的行号 [英] Get record's row number using Linq
问题描述
我想使用Entity Framework 6从表中获取大量记录中的记录行号.
I'd like to get a record's row number inside a huge list of records from a table, using Entity Framework 6.
我尝试了以下代码:
//var currentUser = my record
var orderedUsers = dbContext.User.OrderByDescending(u => u.Age).ToList();
var userIndex = orderedUsers.IndexOf(currentUser);
ToList()
方法由于超时而崩溃,因为我认为该方法会将整个列表加载到内存中.
The ToList()
method crashes with a timeout, because I assume that this methods loads the whole list in memory.
如何在Linq中使用更简单的方法来获得该行号(因此,没有ToList
或将所有内容都安装在内存中)?
How can I get this row number using a simpler method with Linq (so, without ToList
or mounting everything in memory) ?
有关信息,我的目标是获取从起始索引到另一个索引的一系列记录.这是我为此编写的代码:
For information, my goal is to get a range of record from a start index to another index. Here's the code I wrote to do this:
var result = orderedUsers.Skip(userIndex).Take(30).ToList();
谢谢
推荐答案
使用Select
的形式,该形式使用使用索引参数的lambda以及实体:
Use the form of Select
that takes a lambda using an index parameter as well as the entity:
int index = dbContext
.User
.OrderByDescending(u => u.Age)
.Select((user, index) => new {user, index})
.First(x => x.user == currentUser)
.index;
我的目标是获取从起始索引到另一个索引的一系列记录
my goal is to get a range of record from a start index to another index
因此,如果您想在未达到特定记录时跳过,为什么不这样做呢?
So if you want to skip while you haven't reached a particular record, why not just do exactly that:
dbContext
.User
.SkipWhile(x => x != currentUser)
.Take(30);
这篇关于使用Linq获取记录的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!