c# expression func code example

Example 1: c# funtion

public int AddNumbers(int number1, int number2){    int result = number1 + number2;    if(result > 10)    {    return result;    }    return 0;}

Example 2: expression function 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;

Example 3: expression function c#

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

Example 4: create expression func c# for use in where clause

public static Expression<Func<T1, TResult>> ToSimpleFunc<T1, T2, TResult>(Expression<Func<T1, T2, TResult>> f, T2 value)
{
    var invokeExpression = Expression.Invoke(f, f.Parameters[0], Expression.Constant(value));
    return Expression.Lambda<Func<T1, TResult>>(invokeExpression, f.Parameters[0]);
}