문제

I have a Func defined as follows:

Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;

I can query IEnumerables like this:

IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);

But when I try to supply the same Func to the Where method of an IQueryable, I get:

'Cannot convert source type System.Collections.Generic.IEnumerable to System.Linq.IQueryable.'

What's going on? How can I define a Func which will work as a specification for both IEnumerable and IQueryable?

도움이 되었습니까?

해결책

IQueryable's LINQ methods take Expression Trees, not normal delegates.

Therefore, you need to change your func variable to an Expression<Func<Foo, bool>>, like this:

Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;

To use the same variable with an IEnumerable<T>, you'll need to call AsQueryable() or Compile(), like this:

IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top