Search code examples
c#linqlambdaexpression-trees

Create Expression Tree For Selector


Related To :

Create a Lambda Expression With 3 conditions

Convert Contains To Expression Tree

Convert List.Contains to Expression Tree

Please consider above questions.

I want to write a query for this:

using (MyEntities context = new MyEntities())
{
     var DbSet = context.CreateObjectSet<T>();
     var Max = DbSet.Where(exp).Select(selector).Max();
}

I don't know how to write a code for selector. What Select overload I should use? and How I can write that using Expression Tree?

Thanks


Solution

  • What Select overload I should use?

    The one with a single parameter in addition to the source:

    public static IQueryable<TResult> Select<TSource, TResult>(
        this IQueryable<TSource> source,
        Expression<Func<TSource, TResult>> selector
    )
    

    How can I write that using Expression Tree?

    Selector needs to take a TSource parameter, and produce the field of which you want to retrieve the Max. For example, let's say TSource is of type Employee, and you want to find the Max of its Salary property of type decimal. Then you would create an expression tree like this:

    var p = Expression.Parameter(typeof(Employee));
    var m = Expression.Property(p, "Salary");
    var e = Expression.Lambda(m, p);
    var selector = (Expression<Func<Employee,decimal>>)e;