开发者

How parse a string as linq exprssion?

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 ?


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.)


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:

var res = db.Table.Where("CategoryID == 2").Select("CategoryName");

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜