tags:

views:

212

answers:

3

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.

+3  A: 

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.

Sky Sanders
I do not see how this is possible with Dynamic Linq.
Danvil
@Danvil - you are right, your example as written may not be possible, but when you factor out the constants such as... ah hell, i will just edit the answer..
Sky Sanders
+3  A: 

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.

Jon Skeet
+1 but would be concerned about compiling and executing arbitrary code. would require due diligence, and having done such a thing, I say it is no fun and will haunt your dreams. ;-)
Sky Sanders
+1  A: 

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.

Tomas Petricek
I have the data in form of a class and not in a database. I though that by using LINQ, I can perhaps achieve similar interactive queriying behaviour on classes - like SQL queries can do on a database.
Danvil