Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string representation of a Linq To Objects Query

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?

like image 942
eka808 Avatar asked Oct 20 '22 18:10

eka808


2 Answers

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/

like image 112
Roy Dictus Avatar answered Oct 24 '22 12:10

Roy Dictus


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.

like image 27
Servy Avatar answered Oct 24 '22 10:10

Servy