DISTINCT on one column in LINQ to Entities

entity-framework linq linq-to-entities

Question

Is there a way to write following query with Linq to Entities (or Entity SQL, or Method Syntax, or any other way, but I would like to achieve it with Linq to Entities):

SELECT DISTINCT Column1
FROM Table1

I'm using Entity Framework 4. Of course I don't want to use Distinct method that filters data after data is fetched from database.

thanks,Pawel

1
6
12/12/2011 11:38:32 AM

Accepted Answer

Use something like

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

As Munim mentioned in his comment, the Distinct() method does add the DISTINCT to the query. So resulting SQL query will be

SELECT [Distinct1].[Column1] AS [Column1]
  FROM ( SELECT DISTINCT 
    [Extent1].[Column1] AS [Column1]
    FROM [dbo].[Table1] AS [Extent1]
  )  AS [Distinct1]
13
12/12/2011 12:34:11 PM

Popular Answer

For distinct by 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());
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow