如何将字符串解析为 linq 表达式?
我有这个 linq to devforce 表达式:
(from r in mgr.testTables select r).OrderBy(r => r.id);
我想将排序列名称指定为字符串,我需要这样的内容:
string orderBy = "r => r.id";
(从 mgr.testTables 中的 r 选择 r).OrderBy( orderBy );
有没有办法将字符串解析为 linq 表达式?
I've this linq to devforce expression :
(from r in mgr.testTables select r).OrderBy(r => r.id);
I want to specify sorting column name as a string, I need something like this :
string orderBy = "r => r.id";
(from r in mgr.testTables select r).OrderBy( orderBy );
is there any way to parse a string as linq expression ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个完全可操作的表达式解析器示例,它实际上会根据 C# 示例中的字符串为您执行此操作Visual Studio 2008(位于 MSDN 代码库的DynamicQuery 下)。 (
LinqDataSource
控件在内部使用此示例的稍加修改的版本。)There's a sample of a fully operational expression parser that will actually do this for you based on a string in C# Samples for Visual Studio 2008 at MSDN Code Gallery, under DynamicQuery. (The
LinqDataSource
control uses a slightly modified version of this sample internally.)一种选择是使用 动态 LINQ 项目。我认为这与 Ruben 提到的 DynamicQuery 是一样的。不管怎样,它允许您编写如下内容:
动态 LINQ 添加了以字符串作为参数的常用 LINQ 方法的重载。它们将字符串解析为表达式树,然后可由 LINQ 或 LINQ to SQL 使用。
另一种方法是从简单的代码片段(例如访问各种属性的函数以及可用于将它们与值进行比较的各种运算符)组成表达式树。我认为这更优雅并且涉及更少的开销。我在这里写了这种方法,并且有一个名为 PredicateBuilder 使其更简单。
One option is to use Dynamic LINQ project for this. I think this is the same thing as
DynamicQuery
mentioned by Ruben. Anyway, it allows you to write things like:Dynamic LINQ adds overloads of the usual LINQ methods that take string as parameters. They parse the string into an expression tree that can then be used by LINQ or LINQ to SQL.
An alternative is to compose the expression tree from simple pieces of code (such as functions that access various properties and various operators that you can use to compare them against values). I think this is more elegant and involves less overhead. I wrote about this approach here and there is a type named PredicateBuilder that makes it simpler.