将过滤器字符串转换为 C# 委托

发布于 2024-10-23 15:34:55 字数 600 浏览 1 评论 0原文

我有一组类,用于某些客户端的数据访问层。作为数据访问的一部分,我允许以这种格式发送一组过滤器:

"{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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流星番茄 2024-10-30 15:34:56

是的,绝对!这也是一件非常有趣的事情。

执行此操作的一种方法是使用 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文