我有一个 Func 定义如下:
Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
我可以这样查询 IEnumerables:
IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);
但是当我尝试向 IQueryable 的 Where 方法提供相同的 Func 时,我得到:
“无法将源类型 System.Collections.Generic.IEnumerable 转换为 System.Linq.IQueryable。”
这是怎么回事?我如何定义一个 Func 作为 IEnumerable 和 IQueryable 的规范?
最佳答案
IQueryable
的 LINQ 方法采用 Expression Trees ,不是普通代表。
因此,您需要更改您的 func
变量为 Expression<Func<Foo, bool>>
,像这样:
Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
将相同的变量与 IEnumerable<T>
一起使用,您需要调用 AsQueryable()
或 Compile()
,像这样:
IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());
关于c# - 需要 Func 提供给 IEnumerable 和 IQueryable 的 Where() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3523204/