LINQ - 嵌套 WHERE IN 查询

LINQ - Nested WHERE IN query

我有以下 SQL 查询,我想将其转换为 LINQ 表达式。

SELECT `a`.*
FROM `action` AS `a`
WHERE `a`.`id` IN (
    SELECT MAX(`a1`.`id`) AS id
    FROM `action` AS `a1`
    GROUP BY `a1`.`column1`
)

我可以用 LINQ 表达式翻译内部查询:

IQueryable query = from a1 in db.Action
                   group a1 by new { a1.column1 } into grp_a1
                   select new
                   {
                       id = grp_a1.Max(c => c.id)
                   }

但是如何将内部查询作为输入传递给外部查询呢?

您可以使用 LINQ .Any() 来检查 id 是否在嵌套查询的数组中。

IQueryable query = from a in db.Action
                   where 
                   (
                       from a1 in db.Action
                       group a1 by new { a1.column1 } into grp_a1
                       select new
                       {
                           id = grp_a1.Max(c => c.id)
                       }
                   ).Any(x => x.id == a.id)
                   select a;