Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert expression type 'lambda expression' to return type 'System.Linq.Expressions.Expression<System.Func<IProduct,string,bool>>'

Tags:

c#

lambda

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");

    }
like image 947
Robert4Real Avatar asked Jan 23 '23 18:01

Robert4Real


2 Answers

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.

like image 58
womp Avatar answered Jan 30 '23 21:01

womp


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;
}

?

like image 36
Marc Gravell Avatar answered Jan 30 '23 23:01

Marc Gravell