Search code examples
c#.netdynamic-expresso

Parse as expression an array containing specific identifier


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

Solution

  • 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.