DISTINCT on one column in LINQ to Entities

entity-framework linq linq-to-entities

Question

Is it possible to do the following query using Linq to Entities (or Entity SQL, or Method Syntax, or any other manner, although I'd like to do it that way):

SELECT DISTINCT Column1
FROM Table1

Entity Framework 4 is what I use. It goes without saying that I don't want to utilize the Distinct technique, which filters data after it has been obtained from the database.

thanks,Pawel

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

Accepted Answer

Use a device like

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

The DISTINCT is added to the query using the Distinct() function, as Munim indicated in his remark. the final SQL query will thus 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

Use the following extension for distinct by column:

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