简体   繁体   中英

How to build a LINQ query from text at runtime?

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 eg

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.

Dynamic Linq baby!

re comment.

Yes, the example as written may not be possible using Dynamic Linq, but if you factor out the constants, eg '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.

Well, you can use CSharpCodeProvider to compile code at execution time. Have a look at Snippy for an example of this. In this case you'd need to compile the user code in a method which accepts a List<A> called data . My experience is that it works, but it can be slightly fiddly to get right - particularly in terms of adding the appropriate references etc.

Answering it pretty late; though, it will help someone who visits this page.

I had similar requirement and I solved it by dynamically compiling string as LINQ query, executing it over in-memory collection and collecting the result. Only catch is user input needs to be valid C# compile-able code else it returns an exception message instead of result.

Code is pretty long so here is the github link

Sample application on github shows multiple examples including projection.

Although there may be some ways to do this, LINQ simply isn't designed for this scenario. Using CodeDOM (as Jon suggested) is probably the only way to get that easily done. If you trust the user and he/she has programming skills, you could perhaps just use old fashioned methods and let the user enter the query using SQL?

If you, on the other hand, choose to create some visual tool for constructing queries, you don't need to build them by composing strings and you can compose expression trees instead. For example using Linq Kit and AsExpandable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM