Take question RRS feed

  • Question

  • Hi,

    I'm trying to figure out an issue I have with the "Take" method.

    If I filter my IQueryable with some "Where" clause and after it I'm calling the "Take" method with say 1000, then it works fast and returning the correct result.

    I can't understand why it works as it works, I'll try to describe my confusion with an example:

    The LINQ expression which I use:

    MyTable.Where( t => t.Name.Contains("test")).Take(1000)

    Now say I have 300 rows with "test" within their name and the total number of rows in MyTable is 10,000,000, then I would expect that the query will run forever cause it has to run on all the rows until it understand there won't be 1000 results but only 300. However, the query works fast and returns the correct results. By "correct results" I mean that at first I thought that maybe the "Take" happens before the filtering and gets the first 1000 rows and then execute the filtering on it, but it seems that it doesn't work this way.

    Can anyone explain how it works fast enough? How the "Take" method actually do this?



    Wednesday, July 11, 2012 3:51 PM


  • Your linq query will be translated to something like this :

    SELECT TOP (1000) * FROM mytable WHERE name LIKE 'test'

    so, the sql server will fetch the "WHERE" clause that match the criteria, then it will take first 1000.

    The sql will not run all rows, it will select the first 1000 match after the WHERE clause executed.


    Thursday, July 12, 2012 6:49 AM