I'm using the following query syntax
from table
where
where
orderby
orderby
Where the first orderby is a date and second orderby is a date. I would assume this would work like orderby thenby but appears to be doing something else.
How can I do an orderby thenby using the above syntax without using extension syntax. (Got it)
And what does the orderby, orderby do?
Use a comma between the fields:
When you use
orderby
twice in a row the elements conceptually will first be sorted using the firstorderby
, and then sorted again using the secondorderby
. Because the sorting is defined to be a stable sort (objects which are tied with the secondorderby
will remain in the same order as after sorting with the firstorderby
it effectively means that this:is equivalent to:
The result is that the
orderby
terms are swapped from what you probably intended.Testing it with LINQ to SQL
This can be verified by trying it in LINQ to SQL. I created the following query:
and this was the generated SQL:
Note that the
orderby a.Date
is not ignored. Both terms are included in the ORDER BY clause, but in the opposite order than you might have intended.Performing a ThenBy in Query Expression Syntax is straighforward, simply follow the initial orderby with a comma and a 2nd statement:
Applying a 2nd orderby using the standard query operators (extension methods) will actually apply the second orderby to the result of the query result which includes the first orderby. In effect, only the second orderby will apply, although you'll still spend CPU time calculating the first order.
This is actually answered directly in the MSDN documentation for the Enumerable.OrderBy and Enumerable.ThenBy methods.
The
ThenBy
operator applies a secondary, ascending sort order to the sequence. It is akin to applying a secondary sort order in T-SQL like :In linq we can write this as:
You can check more about this here: http://dotnetreaders.com/articles/ThenBy_in_LINQ_c-sharp,_Orderby_Thenby_in_LINQ_C-sharp/204
The answer to the thenby should be like this
orderby 1, 2
I'll leave part #2 for someone else.