Mike_G
Mike_G

Reputation: 16502

Are subqueries in LinqToSql guaranteed to be in the same order as their parent?

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?

Upvotes: 2

Views: 105

Answers (2)

James Curran
James Curran

Reputation: 103535

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...)

Upvotes: 7

BFree
BFree

Reputation: 103750

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.

Upvotes: 1

Related Questions