System.Linq.Dynamic.Core icon indicating copy to clipboard operation
System.Linq.Dynamic.Core copied to clipboard

Question: Lambda invocation

Open zspitz opened this issue 5 years ago • 4 comments

The following:

public class Person {
    public string FirstName {get;set;}
    public string LastName {get;set;}
}
var selector = "(LastName + FirstName)()";
var prm = Expression.Parameter(typeof(Person));
var parser = new ExpressionParser(new[] { prm }, selector, new object[] { }, ParsingConfig.Default);
var expr = parser.Parse(null);

fails with:

System.Linq.Dynamic.Core.Exceptions.ParseException: 'Syntax error'

Changing the selector to:

var selector = "(LastName + FirstName)(it)";

doesn't work either.

How do I define a lambda expression within the selector, and invoke it?

zspitz avatar Oct 28 '20 21:10 zspitz

Would love to know this too. Trying to figure out how to get this to work.

dbfilevine avatar Nov 09 '20 23:11 dbfilevine

@zspitz Can you explain what you are trying to do here? (Maybe provide a normal LINQ example as a reference?)

StefH avatar Dec 01 '20 18:12 StefH

@StefH Something like this:

var qry = new List<Person>().AsQueryable().Where(x => ((Func<string>)(() => x.LastName + x.FirstName))().Length >0);

class Person {
    public string LastName {get;set;}
    public string FirstName {get;set;}
}

I can't recall the precise use case I had for defining a lambda within the Dynamic LINQ selector (@dbfilevine any thoughts here?) but trying to just invoke a delegate using only ( and ), whether passed in from outside using @n parameters:

Func<Person, string> lmbd = p => p.LastName + p.FirstName;
var selector = "@0(it).Length > 0";
var qry1 = lst.AsQueryable().Where(selector, lmbd);

fails with:

Syntax error

However, it is perfectly possible to use the delegate's Invoke instance member:

Func<Person, string> lmbd = p => p.LastName + p.FirstName;
var selector = "@0.Invoke(it).Length > 0";
var qry1 = lst.AsQueryable().Where(selector, lmbd);

which works just fine. I would be fine with the current status -- no way to define a lambda, and invoke using .Invoke.

@dbfilevine Any further thoughts on this?

zspitz avatar Dec 01 '20 20:12 zspitz

The documentation suggests this should be possible:

Category Expression Description
...
Primary x(...) Dynamic lambda invocation used to reference another dynamic lambda expression.

zspitz avatar Jun 23 '21 21:06 zspitz