简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM