首页 > 解决方案 > 将 linq 语句转换为表达式

问题描述

我正在创建一个生成谓词来过滤数据的通用方法。这是我的开始方法

Expression.Call(member, typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), constant);

同样,我需要一个表达式来在字符串列表中查找逗号分隔的字符串。我的解决方案是

filterValue.Split(",").Any(f => messageValue.Contains(f))

我需要将其转换为上述方法以调用为表达式。请帮助..

标签: .netlinqlambdapredicate

解决方案


请自己测试,但我认为这应该有效。您也可以改进此代码。

var filterValue = Expression.Constant("a,b");
var messageValue = Expression.Constant("b");
var separator = Expression.Constant(new char[] { ',' });

var split = typeof(string).GetMethod("Split", new[] { typeof(char[]) });
var contains = typeof(string).GetMethod("Contains", new[] { typeof(string) });

var f = Expression.Parameter(typeof(string), "f");

var lambda = Expression.Lambda(Expression.Call(messageValue, contains, f), f);
var splitted = Expression.Call(filterValue, split, separator);

var expression = Expression.Call(typeof(Enumerable), "Any", new[] { typeof(string) }, splitted, lambda);
bool result = (bool)Expression.Lambda(expression).Compile().DynamicInvoke();

推荐阅读