I am learning about LINQ-to-SQL and everything was going well until something strange happened:
I tried to make an example of distinct, so, using the Northwind dabatase I wrote the following query:
var query =
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
};
If I print the SQL generated by LINQ-to-SQL for the query stored in query it looks like this:
SELECT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
ORDER BY [t0].[CustomerID]
So, as usual, the query brings all the CustomerID for each Order in the Orders table ordered alphabetically.
But! If I use the Distinct() method like this:
var query = (
from o in db.Orders
orderby o.CustomerID
select new
{
o.CustomerID
}).Distinct();
The query brings the expected results of the Distinct clause, but the CustomerIDs are not ordered despite I wrote orderby o.CustomerID!
The SQL query for this second LINQ query is the following:
SELECT DISTINCT [t0].[CustomerID]
FROM [dbo].[Orders] AS [t0]
As we can see **the ORDER BY clause is missing. Why is that?
Why does the ORDER BY clause disappears when I use the Distinct() method?
From the Queryable.Distinct documentation;
In other words, any order the existing IQueryable has is lost when you use
Distinct()on it.What you want is probably something more like this, an OrderBy() after the Distinct() is done;