Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a LINQ query from text at runtime?

Tags:

c#

linq

I have a

class A {
   public int X;
   public double Y;
   public string Z;
   // and more fields/properties ...
};

and a List<A> data and can build a linq query like e.g.

var q = from a in data where a.X > 20 select new {a.Y, a.Z};

Then dataGridView1.DataSource = q.ToList(); displays the selection in my DataGridView.

Now the question, is it possible to build the query from a text the user has entered at runtime? Like

var q = QueryFromText("from a in data where a.X > 20 select new {a.Y, a.Z}");

The point being, that the user (having programming skills) can dynamically and freely select the displayed data.

like image 627
Danvil Avatar asked Apr 18 '10 08:04

Danvil


1 Answers

Dynamic Linq baby!

r.e. comment.

Yes, the example as written may not be possible using Dynamic Linq, but if you factor out the constants, e.g. 'from a in data' you are left with a 'where' and a 'select' which can be expressed with dynamic linq.

so two text boxes, maybe three if you include an orderby, could possibly satisfy your requirements.

Just a thought.

Jon has an interesting approach but i would be leery of compiling and executing unrestrained code.

like image 52
Sky Sanders Avatar answered Oct 18 '22 12:10

Sky Sanders