How can I return first 100 records using Linq?
I have a table with 40million records.
This code works, but it's slow, because will return all values before filter:
var values = (from e in dataContext.table_sample where e.x == 1 select e) .Take(100);
Is there a way to return filtered? Like T-SQL TOP clause?
Accepted Answer. data . GroupBy( x => x.
First will query Take 1, so there is no difference in query. Calling FirstOrDefault will be one step statement, because Take returns IEnumerable do you will need to call First anyway. First will throw exception so FirstOrDefault is always preferred.
No, that doesn't return all the values before filtering. The Take(100)
will end up being part of the SQL sent up - quite possibly using TOP.
Of course, it makes more sense to do that when you've specified an orderby
clause.
LINQ doesn't execute the query when it reaches the end of your query expression. It only sends up any SQL when either you call an aggregation operator (e.g. Count
or Any
) or you start iterating through the results. Even calling Take
doesn't actually execute the query - you might want to put more filtering on it afterwards, for instance, which could end up being part of the query.
When you start iterating over the results (typically with foreach
) - that's when the SQL will actually be sent to the database.
(I think your where
clause is a bit broken, by the way. If you've got problems with your real code it would help to see code as close to reality as possible.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With