I want to use a Linq to Objects query to select certain members from a list based on fairly complex selection criteria (for simplification represented here as return true
:-)
Using the Where extension method, this works just fine:
var matches = (from wm in Members
select wm).Where(p =>
{
return true;
});
However, when I attempt to do the same thing using the query syntax:
var matches2 = (from wm in Members
where (p =>
{
return true;
})
select wm);
The compiler objects
Cannot convert lambda expre开发者_运维百科ssion to type 'bool' because it is not a delegate type
What is going on here behind the scenes, and how can I use a lamda expression with the query syntax?
your query gets translated to something like:
Members.Where(member=> p=>{return true;});
...which doesn't compile because (warning: technical errors probably be here) Where()
expects a parameter of type Func<TSource, bool>
. You are giving it a parameter that would get converted to type Func<TSource, Func<???, bool>>
. The error is telling you that a lambda expression cannot be converted to a bool, because lambda expressions can only be converted to delegate types (e.g. Func<...>
, and bool is not a delegate type.(/end bumbling explanation)
In query syntax, whatever you put in your where
clause goes after the =>
in the lambda expression for the generated Where()
method call. Note that your first snippet can be rewritten as:
Members.Where(p=>true);
which is equivalent to:
from m in members
where true
select m;
if you really need a lambda with a statement block in it you can do:
var lam = (Member m)=> {return true;};
from m in members
where lam(m)
select m;
or to inline it:
from m in members
where ((Func<Member, bool>)(Member m)=> {return true;})(m)
select m;
or you can use a regular method instead of an anonymous one:
public bool DoStuff(int i)
{
return true;
}
...
from m in members
where DoStuff(m)
select m;
精彩评论