Create Expression Tree For Selector

c# expression-trees lambda linq

Question

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

1
1
10/9/2017 12:10:02 PM

Accepted Answer

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;
2
10/9/2017 11:30:50 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow