Alex Rivera | Logout

Selecting first 100 records using Linq

Asked 2009-08-18T20:58:09.230
27

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?

Edit
Report

2 Answers

34

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

answered 2009-08-18T21:01:48.100
2

Have you compared standard SQL query with your linq query? Which one is faster and how significant is the difference?

I do agree with above comments that your linq query is generally correct, but...

  • in your 'where' clause should probably be x==1 not x=1 (comparison instead of assignment)
  • 'select e' will return all columns where you probably need only some of them - be more precise with select clause (type only required columns); 'select *' is a vaste of resources
  • make sure your database is well indexed and try to make use of indexed data

Anyway, 40milions records database is quite huge - do you need all that data all the time? Maybe some kind of partitioning can reduce it to the most commonly used records.

answered 2009-08-18T21:11:39.077

Your Answer