I'm using linq and EntityFramework 6 to limit the number of records returned from database.
My test table, AuditLogs
, has a total of 20 records.
If I write:
var auditLogsList = context.AuditLogs.Take(10); // Type is IQueryable<AuditLog>
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Correct output = 10
I get listValues.Count
equals to 10, which is the expected output.
But, I don't know why, if I call method Take in the next line :
var auditLogsList = context.AuditLogs; // Type is IQueryable<AuditLog>
auditLogsList.Take(10);
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Wrong output = 20
I get listValues.Count
equals to 20, which is the total number of records of the table and it's not what I expect.
I need to use it the second way.
Any ideas if it's a bug or am I missing something here?
Note: I'm using .NET Framework 4.6.1 and Entity Framework 6
This line:
auditLogsList.Take(10);
Just creates an enumerator over 10 items - but you don't assign this anywhere, so it's thrown away.
Later on you do this:
var listValues = auditLogsList.ToList();
This is working with the whole list - hence why you get 20.
If you just want to take 10 items (as a list), you can change the above line to:
var listValues = auditLogsList.Take(10).ToList();
Actually you are using Take
wrong. As MSDN link says that Take will Returns a specified number of contiguous elements from the start of a sequence. So you need to set it to a variable.
var auditLogsList = context.AuditLogs;
auditLogsList = auditLogsList.Take(10);
var listValues = auditLogsList.ToList();
var count = listValues.Count; // output = 10
Hope helps,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.