Reputation: 1392
Ok, I'm lost. Why is the 1st function WRONG (squiglies in the lambda expression), but the 2nd one is RIGHT (meaning it compiles)?
public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
return (h => h.product_name == val);
}
public static Expression<Func<IProduct, bool>> IsValidExpression2()
{
return (m => m.product_name == "ACE");
}
Upvotes: 3
Views: 19019
Reputation: 12050
Before trying to fix the lambda expression be sure that the following references were added to the related cs file:
using System.Linq;
using System.Linq.Expressions;
The lack of these references may cause the same error as well ("Cannot convert lambda expression to type 'System.Linq.Expressions.Lambda Expression' because it is not a delegate type").
Upvotes: -1
Reputation: 116987
Your first function is going to need two arguments. Func<x,y,z>
defines two parameters and the return value. Since you have both an IProduct
and a string
as parameters, you'll need two arguments in your lambda.
public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
return ((h, i) => h.product_name == val);
}
Your second function is only Func<x,y>
, so that means that the function signature has but one parameter, and thus your lambda statement compiles.
Upvotes: 7
Reputation: 21752
Func<IProduct, string, bool>
is a delegate to a method with the following signature:
bool methodName(IProduct product, string arg2)
{
//method body
return true || false;
}
so
public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
return (h => h.product_name == val);
}
has a differance between the return type and the returned value. you are trying to return an object of the type Expression<Func<IProduct, bool>>
.
the val argument is not an argument to the method you're delegating to but will be hoisted (made part of a class implementing the resulting function) and since it's not an argument to the resulting method it should not be part of the Func
type delclaration
Upvotes: 0
Reputation: 1063724
What is the middle string
intended to do? You can make it compile by:
public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
return (h,something) => h.product_name == val;
}
Or maybe you mean:
public static Expression<Func<IProduct, string, bool>> IsValidExpression()
{
return (h,val) => h.product_name == val;
}
?
Upvotes: 3