What is the order in which this function is executed: var queryResult = names.OrderBy (item => item) .Where (it => it.StartsWith ("S"))

what is the order of execution of this function:

var queryResult = names.OrderBy(item => item).Where(it => it.StartsWith("S"))

      

+2


a source to share


3 answers


I am assuming that names

is a projection of a column from a simple table of tables, for example:

var names = ctx.SomeTable.Select(row => row.Name);

      

The good news is that it actually does nothing by itself ; it creates a composite view of the request, which (from outside in):

  • Where

    [predicate]
  • (packing) OrderBy

    [selector]
  • (packing) Select

    [selector]
  • (wrapping) table query


Nothing else happens until you iterate over the data ( foreach

, GetEnumerator()

etc.) or call First

(etc.). Using LINQ to SQL (from tags), it creates a single TSQL query (which makes the "order of execution" a problem only for the db engine itself) suitable for the current connection (specific flavor of SQL Server) that would look something like this:

SELECT row.Name
FROM [dbo].[SomeTable] row
WHERE row.Name LIKE @p1
ORDER BY row.Name

      

probably passing 'S%'

like @p1

.

If it's LINQ-to-Objects, the data is fetched from the outside inside, with each layer querying the inner layers for the data and filtering / processing them as needed. So with LINQ-to-Objects it makes sense to do Where

before OrderBy

. With LINQ-to-SQL, it doesn't matter.

+1


a source


It depends on what names

. If you are using Linq-to-SQL, then it will be compiled into a single SQL statement that ends with:

WHERE `item` LIKE 'S%'
ORDER BY `item` ASC

      



and the database backend is probably running in that order.

As far as working with a normal data structure (for example List<T>

), I agree that they will be executed in left-to-right order.

+1


a source


Simple answer: WHERE

then ORDER BY

.

More complex answer: LINQ query will translate into SQL query (going by your linq-to-sql tag), so this is SQL Server granularity. It usually runs the clause first WHERE

and then orders the results (to save the cost of comparing results that don't even need to be returned), but my guess is that it can do the ordering first if it's ordered by a clustered index or something.

0


a source







All Articles