C# 如何为 List<T> 上的 Exists() 构建表达式树
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);
如何将最后一条语句Exists()转换为表达式树?
您可以 create an expression tree from a lambda expression 然后将其编译成一个函数,然后可以使用 strlist
和 somevalue
参数调用该函数,如下所示:
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);
List<string> strlist = new List<string> { "one","two", "three" };
string somevalue = "two";
var result = strlist.Exists(e2 => e2 == somevalue);
如何将最后一条语句Exists()转换为表达式树?
您可以 create an expression tree from a lambda expression 然后将其编译成一个函数,然后可以使用 strlist
和 somevalue
参数调用该函数,如下所示:
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);