Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL does not generate ORDER BY when DISTINCT is used?

Tags:

People also ask

Why distinct is not working in LINQ?

LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.

Does distinct preserve order?

Java Stream distinct() MethodIf the stream is ordered, the encounter order is preserved. It means that the element occurring first will be present in the distinct elements stream.

How to distinct using LINQ?

If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.

What does distinct do in c#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).


The following basic LINQ to SQL statement does not result in the orderby working. As you can see in the T-SQL there is no orderby. Do you know why?

LINQ to SQL:

      var results = (from stats in db.t_harvest_statistics
                       orderby stats.unit_number
                       select stats.unit_number).Distinct().ToList();

Above Results in following TSQL

SELECT 
[Distinct1].[unit_number] AS [unit_number]
FROM ( SELECT DISTINCT 
[Extent1].[unit_number] AS [unit_number]
FROM [dbo].[t_harvest_statistics] AS [Extent1]
     )  AS [Distinct1]