40

I need a way to recreate dynamically generated reports at some point in the future. Long story short, I need to store a specific linq query (different for each report) into database and then execute the query with dynamic Linq later on.

This is all good, but I can't find a way to convert expression to string.

As in:

Expression<Product, bool> exp = (x) => (x.Id > 5 && x.Warranty != false);

should become:

"Product.Id > 5 && Product.Warranty != false"

Is there a way to do that?

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
  • 2
    I think you are asking `Expression>`, I have modified your question. – Cheng Chen Jan 25 '11 at 13:24
  • Yes, that's correct, I left the func part out. –  Jan 25 '11 at 13:31
  • Perhaps this will help: http://code.msdn.microsoft.com/exprserialization – sinelaw Jan 25 '11 at 13:32
  • What is wrong with `ToString()` ? – leppie Jan 25 '11 at 13:45
  • 1
    @leppie: ToString() apparently returns metadata from reflection, not the actual string representation of the lambda expression. –  Jan 25 '11 at 14:00
  • This is roughly the same question as this: http://stackoverflow.com/questions/217961/serializing-and-deserializing-expression-trees-in-c – kelloti Jan 25 '11 at 13:25
  • possible duplicate of [convert-an-expression-tree-to-source-code-string](http://stackoverflow.com/questions/1402839/convert-an-expression-tree-to-source-code-string) – nawfal Dec 19 '13 at 19:33

1 Answers1

50

This may not be the best/most efficient method, but it does work.

Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);

string expBody = ((LambdaExpression)exp).Body.ToString(); 
// Gives: ((x.Id > 5) AndAlso (x.Warranty != False))

var paramName = exp.Parameters[0].Name;
var paramTypeName = exp.Parameters[0].Type.Name;

// You could easily add "OrElse" and others...
expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
                 .Replace("AndAlso", "&&");


Console.WriteLine(expBody);
// Output: ((Product.Id > 5) && (Product.Warranty != False))
TheCloudlessSky
  • 18,608
  • 15
  • 75
  • 116