Are groups in Linq to Sql already sorted by Count () in descending order?

It does, but I can't find definitive documentation on this.

What I am asking is the result of this query:

from x
in Db.Items
join y in Db.Sales on x.Id equals y.ItemId
group x by x.Id into g
orderby g.Count() descending
select g.First()

      

ALWAYS HAS ALSO the following query:

from x
in Db.Items
join y in Db.Sales on x.Id equals y.ItemId
group x by x.Id into g
select g.First()

      

Note that the second query allows Linq to decide the order of the group that the first query specifies as the number sold, from highest to lowest.

My advertising tests seem to indicate that Linq automatically sorts groups this way, and the documentation seems to indicate that the opposite is true - items are returned in the order they appear in the list. I suppose if it is sorted this way adding the extra sort would be pointless and undo the loops and it would be better not to consider.

0


a source to share


3 answers


You are probably seeing this because the query result returned from sqlserver is always in the same order in your tests. However, this is a fallacy: by definition, there is no ordering in SQL queries unless it is explicitly specified using ORDER BY. Therefore, if your queries are out of order from the operator, your sets may look like they are being ordered, but they are not, perhaps in cases with an edge the order is different (for example, when the server has to load the pages of the table in a different order due to memory limits or otherwise). So a rule of thumb: if you want to order, you must specify it.



+4


a source


LINQ grouping does not guarantee such a thing. While this may work for this particular circumstance, it may not work in another situation. Avoid relying on this side effect .



By the way, if the output is indeed deliberately sorted by SQL Server due to a clustered index or something else, adding a clause ORDER BY

won't hurt, because the query optimizer has to be smart enough to know that the result is already sorted so you won't lose anything.

+1


a source


If the specifications do not warrant ordering, you should consider this to be accidental and subject to change with any new version of the software.

And don't take it out if

a) you have measured it and it makes a difference.

b) you are ready to track, test and change it (everywhere) after every minor change in your software environment.

+1


a source







All Articles