views:

201

answers:

2

It appears so, but I can't find any definitive documentation on the subject.

What I'm asking is if 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()

is ALWAYS THE SAME as 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 lets Linq decide the ordering of the group, which the first query sets as number sold, from most to least.

My ad-hoc tests seem to indicate that Linq automatically sorts groups this way, while the documentation seems to indicate that the opposite is true--items are returned in the order they appear in the select. I figure if it comes sorted this way, adding the extra sort is pointless and wastes cycles, and would be better left out.

+4  A: 

You're likely seeing this because the query result returned from the sqlserver is always in the same order in your tests. However, this is a fallacy: by definition, sets in SQL have no order unless it's explicitly specified with an ORDER BY. So if your queries don't have an order by statement, your sets might look like they're ordered, but that's not the case, it might be that in edge cases the order is different (e.g. when the server has to load pages of the table in different order due to memory constraints or otherwise). So rule of thumb: if you want an order, you have to specify one.

Frans Bouma
+1  A: 

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

By the way, if the output is really intentionally sorted by SQL Server due to clustered index or something, adding an ORDER BY clause won't hurt because query optimizer should be smart enough to know that the result is already sorted, so you won't lose anything.

Mehrdad Afshari