0

I am building dynamic lamda expressions from string expressions using ParseAsExpression. The problem is that i cannot figure out how to parse an expression of an array contains an object like mylist.Contains(x.Id)

Full example

 var list = new int[] { 4,5,6};
 var whereFunction = new Interpreter().SetVariable("mylist", list);    
 whereFunction.ParseAsExpression<Func<Person, bool>>("(person.Age == 5 && person.Name.StartsWith(\"G\")) || person.Age == 3 && mylist.Contains(person.Id)", "person");
George Papadakis
  • 1,273
  • 13
  • 22

2 Answers2

2

For now you can do a workaround by implementing an alias extension method for each method doesn't work, like for Contains=>Exists:

 var list = new int[] { 4,5,6};

 var whereFunction = new Interpreter()
.SetVariable("mylist", list)
.Reference(typeof(ExtensionMethods));

 whereFunction.ParseAsExpression<Func<Person, bool>>("(person.Age == 5 && person.Name.StartsWith(\"G\")) || person.Age == 3 && mylist.Exists(person.Id)", "person");

// Define this class somewhere
public static class ExtensionMethods
{
    public static bool Exists<T>(this IEnumerable arr, T searchKey)
    {
        return ((IEnumerable<T>)arr).Contains(searchKey);
    }
}

I see this is as a stupid workaround, but it'll work.

Dabbas
  • 3,112
  • 7
  • 42
  • 75
  • If this solution worked for you check it as correct answer please. – Dabbas Oct 10 '17 at 13:21
  • Ok i check it but to be true it didnt work for my scenario. Although it creates the expression, it cannot be used as an sql expression in Servicestack Ormlite or entity framework. Waiting for the fix.... – George Papadakis Oct 11 '17 at 10:00
  • It'll not work for SQL for sure, you didn't mention that you wanted it for SQL. this solution only works for linq to object. – Dabbas Oct 12 '17 at 07:06
1

I can confirm this is a bug: https://github.com/davideicardi/DynamicExpresso/issues/68

For now Array.Contains doesn't work.

UPDATE:

Fixed in version 2.0.2.

Davide Icardi
  • 11,919
  • 8
  • 56
  • 77