Search code examples
c#treeexpression-trees

C# How to build an expression tree for Exists() on a List<T>


List<string> strlist = new List<string> { "one","two", "three" };
string somevalue = "two";

var result = strlist.Exists(e2 => e2 == somevalue);

How to convert the last statement Exists() to an expression tree?


Solution

  • You can create an expression tree from a lambda expression and then compile it into a function that can then be invoked with the strlist and somevalue arguments like this:

    var strlist = new List<string> { "one", "two", "three" };
    var somevalue = "two";
    
    Expression<Func<List<string>, string, bool>> expression = (list, value) => 
        list.Exists(item => item == value);
    
    Func<List<string>, string, bool> exists = expression.Compile();
    
    bool result = exists(strlist, somevalue);
    

    Or you could do it all in one line, but it's a little hard to read:

    var exists = ((Expression<Func<List<string>, string, bool>>)
        ((list, value) => list.Exists(item => item == value))).Compile();
    

    But in the end, isn't it simpler to just do:

    bool result = strlist.Contains(somevalue);