无法在 Linq Lambda 表达式中将 System.Collections.Generic.IEnumerable 转换为 bool

Cannot convert System.Collections.Generic.IEnumerable to bool in Linq Lambda expression

我想这应该是直截了当的,但是在 Linq 中将相关 table 过滤为 SQL 的正确方法是什么? 当我通过新连接明确引入辅助 table 时,它会起作用,但我确信对相关 table 的过滤也应该起作用。

例如:

var q = from p in db.Personnel
        where p.PersonnelGifts.Where(p => p.GiftValue >= 2477)
        select {...}

我得到的错误是

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'bool'

var q = from p in db.Personnel
    where p.PersonnelGifts.Where(p => p.GiftValue >= 2477).Any()
    select {...}

或者正如@Jon Skeet 指出的那样 - .Any() 也接受谓词,所以你可以像

这样写
var q = from p in db.Personnel
    where p.PersonnelGifts.Any(p => p.GiftValue >= 2477)
    select {...}

为什么您的代码不起作用? .Where() returns IEnumerable (或 IQueryable 就此而言),因此您可以将它与另一个接受 IEnumerable 作为参数的 LINQ 方法链接起来。您的 where 子句需要 bool 值,而 .Any() 方法恰好返回此类型。