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

问题描述 投票:-1回答:1
List<string> strlist = new List<string> { "one","two", "three" };
string somevalue = "two";

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

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

c# tree expression-trees
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.