Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first 100 records using Linq

Tags:

c#

linq

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?

like image 495
Zanoni Avatar asked Aug 18 '09 20:08

Zanoni


People also ask

Which function is used to get first record in a LINQ collection?

Accepted Answer. data . GroupBy( x => x.

What is the difference between first () and take 1 in LINQ?

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.


1 Answers

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

like image 99
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet