【问题标题】:LINQ to Entities - DISTINCT on one columnLINQ to Entities - 一列上的 DISTINCT
【发布时间】:2011-12-12 11:38:32
【问题描述】:

有没有办法用 Linq to Entities(或 Entity SQL,或方法语法,或任何其他方式,但我想用 Linq to Entities 来实现)编写以下查询:

SELECT DISTINCT Column1
FROM Table1

我正在使用 Entity Framework 4。当然我不想使用从数据库中获取数据后过滤数据的 Distinct 方法。

谢谢,帕维尔

【问题讨论】:

  • Distinct 方法实际上将DISTINCT Column1 添加到您生成的查询中

标签: linq entity-framework linq-to-entities


【解决方案1】:

使用类似的东西

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

正如 Munim 在他的评论中提到的,Distinct() 方法确实将 DISTINCT 添加到查询中。所以生成的 SQL 查询将是

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

【讨论】:

    【解决方案2】:

    对于按列区分,请使用此扩展名:

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

    【讨论】:

    • 注意* 使用此方法将意味着该语句将不再保持 IQueryable。
    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    相关资源
    最近更新 更多