C#如何在List <t>上为Exists()构建表达式树

时间:2019-04-09 21:50:07

标签: c# tree expression-trees

proxy2:8082

如何将最后一条语句Exists()转换为表达式树?

1 个答案:

答案 0 :(得分:0)

您可以create an expression tree from a lambda expression,然后将其编译为一个函数,然后可以使用strlistsomevalue这样的参数来调用该函数:

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

或者您可以全部完成所有操作,但是很难阅读:

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

但是最后,做起来并不容易吗?

bool result = strlist.Contains(somevalue);