views:

55

answers:

3

what is the order of this function's execution:

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

The simple answer is: WHERE, then ORDER BY.

The more complex answer is: the LINQ query would be translated to an SQL query (going by your linq-to-sql tag), so it's a SQL server implementation detail. Usually it would run the WHERE clause first and then order the results (to save the cost of comparing results that don't even need to be returned), but I suppose it might do the ordering first if it's being ordered by a clustered index or something like that.

Evgeny
+1  A: 

It depends on what names is. If you are using Linq-to-SQL then it will be compiled into one SQL query that ends:

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

and likely done in that order by the database backend.

As for operating on a normal data structure (such as a List<T>) I would agree with astander that they will be executed in left to right order.

Jake Wharton
+1  A: 

I'm assuming that names is a projection of a column from a simple table map, such as:

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

Well, that by itself doesn't actually do any execution; it builds a composed query representation that is (from the outside in):

  1. Where [predicate]
  2. (wrapping) OrderBy [selector]
  3. (wrapping) Select [selector]
  4. (wrapping) a table query

Nothing else happens until you either iterate the data (foreach, GetEnumerator(), etc) or call First (etc). With LINQ-to-SQL (from the tags) it then builds a single TSQL query (making the "order of execution" a problem only for the db engine itself) suitable for the current connection (the specific SQL-Server flavour), which will look something like:

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

probably passing 'S%' as @p1.

If this were LINQ-to-Objects, data is fetched from the outside in, with each layer asking inner layers for data and filtering/manipulating it as necessary. As such, with LINQ-to-Objects it makes sense to do the Where ahead of the OrderBy. With LINQ-to-SQL it won't matter.

Marc Gravell