Get a string representation of a Linq To Objects query

In a web application, I have linq To Object queries to retrieve / consolidate data. To simplify debugging, I would like to show the linq query structure directly in the generated HTML; sort of

Bananas
  ->Where color='blue'
  ->Where size>'20cm'
  ->Take 25

In fact, a representation of an expression tree.

Is it possible? How?

+4
source share
3 answers

Just call ToStringin the request. Obviously, you need to create the string as IQueryableusing the extension method AsQueryable, not how IEnumerable.

In 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();

Holds this line:

System.Int32 []. Where (n => ((n% 2) == 0)). Take (25)

, , , , ; , , , .

+1

following from Roy's answer, there is an ongoing project with code that solves the same problem, but alos shows the full expression tree, as well as the final final linq expression in plain English:

http://exprtreevisualizer.codeplex.com/

it really looks like a good tool, but I had to admit, I did not try in vs2012, but I knew and looked in vs2010. I'm not sure if the versions for vs2012 have been expanded, but that certainly does pretty much what you mention.

0
source

All Articles