Expression in LINQ

Take the reference of System.Linq.Expressions namespace and use an Expression<TDelegate> class to define an Expression. Expression<TDelegate> requires delegate type Func or Action.


For example, you can assign lambda expression to the isTeenAger variable of Func type delegate, as shown below:


Define Func delegate for an expression in C#

public class Student 
{
  public int StudentID { get; set; }
  public string StudentName { get; set; }
  public int Age { get; set; }
}

Func<Student, bool> isTeenAger = s => s.Age > 12 && s.Age < 20;


And now, you can convert the above Func type delegate into an Expression by wrapping Func delegate with Expression, as below:


Define Expression in C#

Expression<Func<Student, bool>> isTeenAgerExpr = s => s.Age > 12 && s.Age < 20;


In the same way, you can also wrap an Action<t> type delegate with Expression if you don't return a value from the delegate.


Define Expression in C#

Expression<Action<Student>> printStudentName = s => Console.WriteLine(s.StudentName);


You can invoke the delegate wrapped by an Expression the same way as a delegate, but first you need to compile it using the Compile() method. Compile() returns delegateof Func or Action type so that you can invoke it like a delegate.


Invoke Expression in C#

Expression<Func<Student, bool>> isTeenAgerExpr = s => s.Age > 12 && s.Age < 20;

//compile Expression using Compile method to invoke it as Delegate
Func<Student, bool> isTeenAger = isTeenAgerExpr.Compile();
       
//Invoke
bool result = isTeenAger(new Student(){ StudentID = 1, StudentName = "Steve", Age = 20});

Output: false