将过滤器字符串转换为 C# 委托
我有一组类,用于某些客户端的数据访问层。作为数据访问的一部分,我允许以这种格式发送一组过滤器:
"{Member[.Member....]}{Operator}{Value}"
我想将这些字符串转换为委托,以便在 LINQ 查询中使用,如下所示:
.Where([delegate returned by a factory])
这是一个更具体的示例:
IEnumerable<Parent> parents = GetSomeParents();
string filter = "Child.Id=5";
var expression = FilterFactory<Parent>.GetExpression(filter);
parents = parents.Where(expression);
表达式将包含委托: 父 => parent.Child.Id == 5
有没有一种方法使用反射以通用方式构造 FilterFactory 来处理我发送的任何成员路径?带索引的路径不是必需的,但会很好。
I have a set of classes which I am using for a Data Access Layer for some clients. As part of the data access I am allowing a set of filters to be sent in this format:
"{Member[.Member....]}{Operator}{Value}"
I would like to turn these strings into delegates for use in a LINQ query like this:
.Where([delegate returned by a factory])
Here is a more concrete example:
IEnumerable<Parent> parents = GetSomeParents();
string filter = "Child.Id=5";
var expression = FilterFactory<Parent>.GetExpression(filter);
parents = parents.Where(expression);
expression would contain the delegate: parent => parent.Child.Id == 5
Is there a way using reflection to construct the FilterFactory in a Generic way to handle any member path I send in? Paths with indexing aren't required, but would be nice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,绝对!这也是一件非常有趣的事情。
执行此操作的一种方法是使用 LINQ 动态查询库 并获取其中的表达式编译器。我的项目 MetaSharp 中也有一些非常相似的东西。
但如果语法或功能与您想要的不太匹配,您也可以自己完成。总体思路是,您需要解析字符串并构建一个表示您正在解析的内容的表达式树。在 .NET 中,表达式树对象可以在 System.Linq.Expressions 中找到。一旦你有了你的树,你就可以在它上面调用 Compile() ,然后它就会被动态编译成委托。尝试阅读有关状态机和访问者模式的信息,以找出解析上面的任意表达式的最佳方法。
PS 我不建议使用正则表达式!
Yes absolutely! This is a really fun thing to do too.
One way you can do this is to use the LINQ Dynamic Query Library and get the expression compiler they have in there. I also have something very similar in my project MetaSharp.
But you could also do it yourself if the syntax or features don't quite match what you're wanting. The general idea is that you need to parse the string and build up an Expression tree that represents what you are parsing. In .NET the expression tree objects can be found in System.Linq.Expressions. Once you have your tree you can call Compile() on it and it will be dynamically compiled into a delegate right then. Try reading about the State Machine and Visitor patterns to figure out the best way to parse an arbitrary expresssion like you have above.
PS I would not recommend using regular expressions!