views:

55

answers:

2

lets say i have a table with a DateTime field and a int field and perform a query like this:

var query = context.tblSomeTable.Where(s=>s.Name == "Hello World").OrderBy(s=>s.SignUpDate);

if I then perform two subqueries with the result, are they still ordered by the date?:

var sub1 = query.Where(s=>s.Id = 5);
var sub2 = query.Where(s=>s.Id = 8);

My gut says they are still in order, but does it matter if the original query has been iterated/executed yet?

+1  A: 

Yes, it still stays in the same order. The first query in your case, will be an IOrderedQueryable and when you query that further, the sub1 and sub2 will also be IOrderedQueryable's and therefore will maintain the ordering.

BFree
+7  A: 

Yes, however, it's wrong to say that they are "still" ordered. They are ordered once, at the end.

The important thing to note about LinqtoSql is that it merely builds a query, which is executed when it is used. In the example you shown, you haven't actually used the query yet. You've just build two big queries

They will both generate this SQL statement:

select * from tblSomeTable s
where s.Name = 'Hello World' and s.ID == @p1
order by s.SignUpDate

When you use sub1, @p1 will be set to 5

(Actually, 'Hello World' will be pass as a parameter as well...)

James Curran
This is quite easy to test by using SQL Server Profiler. Put a break point in your code where you're creating your LINQ query, and then step through each line while watching the profiler. You'll know exactly when the query hits the database. This works great for debugging the queries as well, since you can see them and grab them from the profiler.
Jagd
Is there actually anything in the documentation that states that the order By clause will be pushed back to the end? Given the fact that L2S is usually trying to do the "thing that makes sense" I would assume it should, but if it is not stated, do not depend on it and move your "order by" to the end...
Denis Troller
The SQL statement is executed only once --- when the query is actually used (in a foreach statement, or with a .ToList() call for example
James Curran