使用Count with Take with LINQ

Kei*_*ler 2 c# linq

使用Take运算符时,有没有办法获得整数?

luk*_*uke 6

你可以做到这两点.

IEnumerable<T> query = ...complicated query;
int c = query.Count();
query = query.Take(n);
Run Code Online (Sandbox Code Playgroud)

只需在拍摄前执行计数.这将导致查询执行两次,但我相信这是不可避免的.

如果这是在Linq2SQL上下文中,正如您的注释所暗示的那么这实际上将查询数据库两次.就延迟加载而言,它将取决于实际使用查询结果的方式.

例如:如果您有两个表Product,ProductVersion并且每个表Product都有多个ProductVersions通过外键关联的表.

如果这是您的查询:

var query = db.Products.Where(p => complicated condition).OrderBy(p => p.Name).ThenBy(...).Select(p => p);
Run Code Online (Sandbox Code Playgroud)

您只是在选择Products但执行查询后:

var results = query.ToList();//forces query execution
results[0].ProductVersions;//<-- Lazy loading occurs
Run Code Online (Sandbox Code Playgroud)

如果您引用任何不属于原始查询的外键或相关对象,那么它将被延迟加载.在您的情况下,计数不会导致任何延迟加载,因为它只是返回一个int.但取决于你实际使用的结果,Take()你可能会或可能不会发生延迟加载.有时候很难判断你是否有LazyLoading ocurring,要检查你是否应该使用该DataContext.Log属性记录你的查询.