我正在try 为Eumerable.Any(IEnumerable,Func<T,bool>)创建表达式树

实际上,我有一个列表,需要判断该列表是否至少有一个包含"test"的元素

所以看起来很简单:

List<string> strings = new List<string> { "element1", "element2", "element3" };
var test = strings.Any(x => x.Contains("test"));

我正在try 创建表达式树,而GetMethod返回NULL,所以我想我错过了一些东西

以下是一个测试代码:

List<string> strings = new List<string> { "element1", "element2", "element3" };
var testString = "test";
ParameterExpression p = Expression.Parameter(typeof(string), "item");
            
Delegate predicate = Expression.Lambda(
Expression.Call(
p,
typeof(string).GetMethod("Contains", new[] { typeof(string) }),
Expression.Constant(testString)),
p).Compile();
Type predType = typeof(Func<,>).MakeGenericType(typeof(string), typeof(bool));

// Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
System.Reflection.MethodInfo anyMethod = typeof(Enumerable).GetMethod("Any", new Type[] {typeof(IEnumerable<string>), predType});
    
Expression anyCall = Expression.Call(
    anyMethod,
    Expression.Constant(strings),
    Expression.Constant(predicate));    

// test
Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();

谢谢!

推荐答案

try 以下操作:

var p = Expression.Parameter(typeof(string), "x");
var strParam = Expression.Parameter(typeof(string), "str");
            
// x.Contains(str)
var boyd = Expression.Call(p, nameof(string.Contains), Type.EmptyTypes, strParam);

// x => x.Contains(str)
var lambdaExpression =  Expression.Lambda<Func<string, bool>>(body, p);

var enumerableParam = Expression.Parameter(typeof(IEnumerable<string>), "e");

// e.Any(x => x.Contains(str))
var anyCall = Expression.Call(typeof(Enumerable), nameof(Enumerable.Any), new[]{ typeof(string) }, enumerableParam, lambdaExpression);

// e => e.Any(x => x.Contains(str))
var anyLambda = Expression.Lambda<Func<IEnumerable<string>, string, bool>>(anyCall, enumerableParam, strParam)

// Func<IEnumerable<string>, string, bool>>
var complied = anyLambda.Compile();

// test

List<string> strings = new List<string> { "element1", "element2", "element3" };
var testString = "test";

var result = complied(strings, testString);

Csharp相关问答推荐

使用WinSCP和C#将文件从STP服务器上的一个目录复制到另一个目录

Umbraco Lucene日期字段编码转换为.net日期时间

由于小数,如何将一个数字四舍五入到下一个数字?

当MD5被废弃时,如何在Blazor WASM中使用它?

Serilog SQL服务器接收器使用UTC作为时间戳

. NET Core DB vs JSON模型设计

当我使用NET6作为目标框架时,为什么DotNet使用NET8作为MS包?

在多对多关系上不删除实体

如何在NodaTime中为Instant添加一年?

Quartz调度程序不调用作业(job)类

Mongo作为.NET中Testcontainers的副本集

如何将MongoDB序列化程序设置为内部对象属性

我如何让我的秒表保持运行场景而不重置

DbContext-传递自定义配置选项

如何返回具有泛型的类?

Azure函数-在外部启动类中生成配置时出错

这是否比决定是否使用ConfigureAWait(False)更好?

用MongoDB c#驱动程序删除和返回嵌套数组中的文档

使用可空引用类型时C#接口实现错误

如何使用IHostedService添加数据种子方法