-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathExpressionTreeTranslationSampleTwo.cs
32 lines (27 loc) · 1.24 KB
/
ExpressionTreeTranslationSampleTwo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System.Linq.Expressions;
namespace ExpressionTreeSamples;
public class ExpressionTreeTranslationSampleTwo : Sample
{
public override string Name { get; } = "Translation Expression Trees, Sample 2: Computing the sum of an addition tree";
public override void Run()
{
var one = Expression.Constant(1, typeof(int));
var two = Expression.Constant(2, typeof(int));
var three = Expression.Constant(3, typeof(int));
var four = Expression.Constant(4, typeof(int));
var addition = Expression.Add(one, two);
var add2 = Expression.Add(three, four);
var sum = Expression.Add(addition, add2);
// Declare the delegate, so we can call it
// from itself recursively:
Func<Expression, int> aggregate = null!;
// Aggregate, return constants, or the sum of the left and right operand.
// Major simplification: Assume every binary expression is an addition.
aggregate = (exp) =>
exp.NodeType == ExpressionType.Constant ?
(int)((ConstantExpression)exp).Value :
aggregate(((BinaryExpression)exp).Left) + aggregate(((BinaryExpression)exp).Right);
var theSum = aggregate(sum);
Console.WriteLine(theSum);
}
}