.net - 将 linq 语句转换为表达式
问题描述
我正在创建一个生成谓词来过滤数据的通用方法。这是我的开始方法
Expression.Call(member, typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), constant);
同样,我需要一个表达式来在字符串列表中查找逗号分隔的字符串。我的解决方案是
filterValue.Split(",").Any(f => messageValue.Contains(f))
我需要将其转换为上述方法以调用为表达式。请帮助..
解决方案
请自己测试,但我认为这应该有效。您也可以改进此代码。
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();
推荐阅读
- react-native - MobX React Native 抛出无法读取未定义的属性
- java - 在 aa jsp 文件中显示来自购物车类的项目时,值将覆盖前一个(会话)
- android - 以编程方式记录 SSL 证书
- css - jQuery-ui-Slider-Pips 阿拉伯语支持
- jquery - 在页面重新加载时保持活动类在导航中
- vb.net - 如何在 vb.net 的主窗体之前调用子窗体
- node.js - Node.Js MongoDB format date while getting List
- scala - 尽管连接条件很重要,但 Spark 检测到笛卡尔积
- android - Starting session in Appium
- r - 在 Shiny Dashboard 中强制刷新