Search code examples
c#linqdebuggingexpression-trees

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?


Solution

  • 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.