tags:

views:

289

answers:

2

Code:

 var result = db.rows.Take(30).ToList().Select(a => AMethod(a));

db.rows.Take(30) is Linq-To-SQL

I am using ToList() to enumerate the results, so the rest of the query isn't translated to SQL

Which is the fastest way of doing that? ToArray()?

+11  A: 

Use Enumerable.AsEnumerable:

var result = db.rows
               .Take(30)
               .AsEnumerable()
               .Select(a => AMethod(a));
Jason
For those that don't click into the link, all AsEnumerable does is return its argument typed as IEnumerable<T>. This will preserve deferred execution and eliminate the need for the intermediate data structure created by ToList() or ToArray().
dahlbyk
+2  A: 

Use Enumerable.AsEnumerable() if you don't want to execute the database query immidiatly because because AsEnumerable() will still deffer the database query execution until you start enumerating the LINQ to Object query.

If you are sure that you will require the data and/or want to immidiatly execute the database query, use Enumerable.ToList() or Enumerable.ToArray(). The performance difference should be not to big.

I assume the rows are read into a variable sized container at first in both call, because the number of rows is not yet known. So I tend to say that ToList() could be a bit faster, because the rows could be directly read into the list while ToArray() probably reads the rows into a kind of list at first and then copies to an array after all rows have been transfered.

Daniel Brückner