LINQ to Entities - DISTINCT on one column

Is there a way to write the following query with Linq to Entities (or Entity SQL, or method syntax or any other way, but I would like to achieve this with Linq for Entities):

SELECT DISTINCT Column1 FROM Table1 

I am using Entity Framework 4. Of course, I do not want to use the Distinct method, which filters data after receiving data from the database.

thanks pawel

+4
source share
2 answers

Use something like

 db.Table1.Select(t => t.Column1).Distinct() 

As Munim mentioned in his comment, the Distinct () method adds DISTINCT to the query. Thus, the result of the SQL query will be

 SELECT [Distinct1].[Column1] AS [Column1] FROM ( SELECT DISTINCT [Extent1].[Column1] AS [Column1] FROM [dbo].[Table1] AS [Extent1] ) AS [Distinct1] 
+8
source

For a single column, use this extension:

 public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) { return items.GroupBy(property).Select(x => x.First()); } 
0
source

All Articles