1

I need to print a linq expression as it is written in the source code. I have searched for solutions, but so far the recommendation is to use expr.ToString().

This won't work for me. For example, if I have an expression:

Expression<Func<int, int>> expr = v => v + 1;

ToString() would return v => (v + 1)

Now if I make a minor modification to the above case

var a = 3;
Expression<Func<int, int>> expr = v => v + a;

then ToString() returns v => (v + value(Program+<>c__DisplayClass0_0).a). I am looking for something like v => (v + a)

My current use case is that I have a set of rules declared as Expression<Func<TSource, ValidationResult>>, then I need to benchmark how long it took to execute them, and for that I need to label them properly. ToString() on a rule will produce a string that is not very readable; just like the above example anything not defined in the calling class will be prefixed with a long string indicating where the token is from.

4
  • I don't think it's possible to print out a string containing the original source. Commented Mar 22, 2019 at 20:59
  • 4
    You would need to parse the expressions pody into its atomic parts. What if your expression was v => v + myMethod()? There´s no single solution to this, you have to do this yourself. Commented Mar 22, 2019 at 21:00
  • As I was reminded in another context, local references are lifted into compiler generated classes in lambda expressions, but I don't see why a Regex removal of value(.+)\. wouldn't be good enough? Commented Mar 23, 2019 at 0:20
  • As mentioned in a comment to @Xiaoy312's answer Regex-based solution has issues, e.g., with calling static methods of another class. Commented Mar 23, 2019 at 19:35

1 Answer 1

1

You can use ReadableExpressions to pretty print it:

var a = 3;
Expression<Func<int, int>> expr = v => v + a;

expr.ToReadableString(); // "v => v + a"
Sign up to request clarification or add additional context in comments.

2 Comments

Nice package. Documentation: github.com/AgileObjects/ReadableExpressions
With the package I found something. If one creates an expression in some class and calls an instance method of the class in the expression the method call is displayed as static which is not quite correct. I tryed to remove matches to regular expression @"value\(.*?\)\.", but it has its issies too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.