Michael Minton
Michael Minton

Reputation: 4495

Parsing Expressions as a parameter

I'm trying to write a method which can be called like this:

var myCommand = Command.Where(x => x.Name == "grep" && x.Switch == "x");

What I'm trying to do is parse the resulting expression like so:

public static string FindBy(Expression<Func<T, bool>>  expression)
{
    var condition1Key = ? //condition1Key = "Name"
    var condition1Value = ? //condition1Value = "grep"
    var condition2Key = ? //condition1Key = "Switch"
    var condition2Value = ? //condition1Value = "x"
    
   return string.Format("Looking for commands with {0} = {1} and {2} = {3}",
                         condition1Key, condition1Value, 
                         condition2Key, condition2Value);
}

I did find this post but it is quite old and never received a proper answer.

How can I parse the incoming Expression to pull out what I need?

Upvotes: 2

Views: 4618

Answers (2)

Attila
Attila

Reputation: 28762

If you follow the links in the SO thread you mentioned, you arrive at the MSDN entry for expressions. Particularly, under the "Parsing Expression Trees" section, the following example should help:

// Create an expression tree.
Expression<Func<int, bool>> exprTree = num => num < 5;

// Decompose the expression tree.
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation = (BinaryExpression)exprTree.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
ConstantExpression right = (ConstantExpression)operation.Right;

Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",
              param.Name, left.Name, operation.NodeType, right.Value);

// This code produces the following output:
// Decomposed expression: num => num LessThan 5    

You can even create a class to make the walking on the tree easier: How to: Implement an Expression Tree Visitor

Upvotes: 2

Rob Rodi
Rob Rodi

Reputation: 3494

You can parse the Expression tree. Here's a basic example from MSDN: http://msdn.microsoft.com/en-us/library/bb397951.aspx

And more from a blog post: http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx

And a great answer on here: https://stackoverflow.com/a/239359/29093

Upvotes: 2

Related Questions