In a web application, I have linq To Object queries to make data extraction/consolidation. To allow easier debugging, I would like to show directly in the generated HTML the linq query structure; something like
Bananas
->Where color='blue'
->Where size>'20cm'
->Take 25
Indeed, a representation of the expression tree.
Is it possible? How?
You can do that, but you'll have to write your own expression tree visitor (a class deriving from ExpressionVisitor
). That is, you have to write code that traverses the Expression Tree that is your LINQ query and builds up the string you want.
For more about expression tree visitors, see http://msdn.microsoft.com/en-us/library/bb882521(v=vs.90).aspx.
There's actually a very interesting example on the Web that does most of this work already: http://pelebyte.net/blog/2011/05/13/doing-simple-things-with-expressionvisitor/
Just call ToString
on the query. Obviously you'll need to have built up the string as an IQueryable
using the AsQueryable
extension method, rather than as an IEnumerable
.
This example:
var list = new int[] { 1, 2, 3, 4, 5 };
var query = list.AsQueryable()
.Where(n => n % 2 == 0)
.Take(25);
string querystring = query.ToString();
Yields this string:
System.Int32[].Where(n => ((n % 2) == 0)).Take(25)
If it's important that you have your own particular formatting, rather than using this default formatting, then you can handle it on your own, but that is opening a pretty big can of worms; be sure you really need it if that's what you want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With