Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 需要Func向IEnumerable和IQueryable的Where()方法提供_C#_Linq_Functional Programming_Specification Pattern - Fatal编程技术网

C# 需要Func向IEnumerable和IQueryable的Where()方法提供

C# 需要Func向IEnumerable和IQueryable的Where()方法提供,c#,linq,functional-programming,specification-pattern,C#,Linq,Functional Programming,Specification Pattern,我有一个Func定义如下: Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers; Func IsSuperhero=x=>x.wearsunderpantsoutsidestants; 我可以这样查询IEnumerables: IEnumerable<Foo> foos = GetAllMyFoos(); var superFoos = foos.Where(IsSuperher

我有一个Func定义如下:

Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
Func IsSuperhero=x=>x.wearsunderpantsoutsidestants;
我可以这样查询IEnumerables:

IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);
Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());
IEnumerable foos=GetAllMyFoos();
var superFoos=foos.Where(IsSuperhero);
但当我尝试为IQueryable的Where方法提供相同的Func时,我得到:

“无法将源类型System.Collections.Generic.IEnumerable转换为System.Linq.IQueryable。”


发生什么事了?如何定义一个同时作为IEnumerable和IQueryable规范的Func?

IQueryable
的LINQ方法采用,而不是普通委托

因此,您需要将
func
变量更改为
表达式,如下所示:

IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);
Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());

但是我不能用它来查询IEnumerables!!!当然,一定有一种方法可以将相同的规范用于两者?@David:这种行为是必要的
IQueryable
用于LINQ到SQL之类的东西,需要了解委托的作用。对于普通的委托,这是不可能的,所以他们必须使用
表达式!我想我离理解这一点还有很长的路要走,但谢谢你的指点!)@David,这是值得学习的,因为表情树非常非常酷。它们编码有关表达式含义的信息,而不是简单地生成执行函数的代码。系统可以很好地利用这些信息做一些有趣、聪明的事情,比如将强类型的.NET表达式转换为标准SQL查询。谢谢。我知道它们被用来将一组条件转换成另一种形式(例如SQL或LDAP查询),但对我来说,这种转换方式是在一个遥远的充满魔力的迷雾之地进行的。但情况可能并非总是如此!