Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

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/

following on from Roy's answer, there is actally a codeplex project that tackles the same problem but alos shows the entire expression tree, as well as the resulting final linq expression in plain english:

http://exprtreevisualizer.codeplex.com/

this actually looks like a nice little tool, tho I have to confess, I haven't tried in vs2012 but have been aware of and looked at in vs2010. I'm not sure if there have been extended versions for vs2012 created, but this certainly does pretty much what you mention.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top