using Microsoft.CodeAnalysis.CSharp.Syntax; // Create an expression syntax tree var expression = SyntaxFactory.ParseExpression("a + b * c"); // Get a collection of all nodes and sub-nodes in the tree var nodes = expression.DescendantNodesAndSelf(); // Loop through the collection and print out each node foreach (var node in nodes) { Console.WriteLine(node.Kind()); }
using Microsoft.CodeAnalysis.CSharp.Syntax; // Create an expression syntax tree var expression = SyntaxFactory.ParseExpression("a + b * c"); // Get a collection of all binary expressions in the tree var binaryExpressions = expression.DescendantNodesAndSelf() .OfTypeIn this example, we create an expression syntax tree in the same way as Example 1. We then use the DescendantNodesAndSelf method to get a collection of all binary expressions in the tree, by filtering the nodes to only include instances of the BinaryExpressionSyntax type. Finally, we loop through the collection and print out the kind of operator used in each binary expression. Overall, the ExpressionSyntax.DescendantNodesAndSelf method is a useful tool for traversing and manipulating expression syntax trees in C#.(); // Loop through the collection and print out the operator of each binary expression foreach (var binaryExpression in binaryExpressions) { Console.WriteLine(binaryExpression.OperatorToken.Kind()); }