views:

30

answers:

2

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 ?

+1  A: 

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.

Tomas Petricek
A: 

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

Ruben