views:

216

answers:

3

Does it take the number specified and stop while querying or after the entire list is already in the collection?

WHat performance benefit if any is there when uysing 'take'?

+3  A: 

All of the querying happens at enumeration.

Performance wise, Take should be able to determine the most efficient way to Grab a number of items.

That means transfoming into a "TOP n" statement in Linq to SQL.

.

My Result from (q.Take(10)).ToString():

SELECT TOP (10) [t0].[UserID], [t0].[RoleID]
FROM [dbo].[UsersRoles] AS [t0]

.

And, the result from (q.Skip(10).Take(10)).ToString():

SELECT [t1].[UserID], [t1].[RoleID]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [t0].[UserID], [t0].[RoleID]) AS [ROW_NUMBER], [t0].[UserID], [t0].[RoleID]
    FROM [dbo].[UsersRoles] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
John Gietzen
what if I do 'Orderby' FIrst?
zsharp
All of those operations are deferred to the SQL Server, so it can use indexes, and etc. to give the best performance possible.
John Gietzen
+1  A: 

You will only get the number of records specified returned from the database, the filtering is done in the SQL.

Slace
what if i do 'Orderby' First?
zsharp
no difference. The expression tree will translate to the same sql
Slace
+1  A: 

The other answers were with respect to LINQ to SQL which is also in the tags but it's worth mentioning that LINQ to Objects will do what you suggested. Effectively doing something like this:

int i = 0;
foreach (var item in items) {
    if ( i++ < count ) {
        yield return item;
    }
}

So in other words it takes only as much as it needs and stops as soon as it can.

And obviously a consequence of this means that:

var c = items.Take(10);  // not yet enumerated
c.Count();  // enumerated the first 10
c.Count();  // enumerated the first 10 again
Josh Einstein