Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to enumerate using LINQ?

Tags:

c#

.net

linq

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()?

like image 358
Jader Dias Avatar asked Jul 08 '09 18:07

Jader Dias


People also ask

When should you use LINQ in your program?

Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it. Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time.

How use any LINQ query?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

How do you write LINQ?

There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.


2 Answers

Use Enumerable.AsEnumerable:

var result = db.rows
               .Take(30)
               .AsEnumerable()
               .Select(a => AMethod(a));
like image 84
jason Avatar answered Nov 14 '22 23:11

jason


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.

like image 20
Daniel Brückner Avatar answered Nov 14 '22 22:11

Daniel Brückner