Michael Schnerring
Michael Schnerring

Reputation: 3661

method with a return type of "Expression"

Is it possible to create a method which returns a lambda expression? I couldn't find any proper examples.

The following syntax doesn't work, of course. It's just to visualize my idea a bit:

// Executed code
var filteredList = listWithNames.Where(GetLambdaExpression("Adam"));

// method
public Expression GetLambdaExpression(string name)
{
    return listElement => listElement.Name == name;
}

Upvotes: 2

Views: 184

Answers (5)

Richard
Richard

Reputation: 22016

You can create functions which return expressions such as this as a simple example in a predicate builder:

public static Expression<Func<T, bool>> True<T>() { return param => true; }

or this expression builder:

static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
                      var map = first.Parameters
                .Select((f, i) => new { f, s = second.Parameters[i] })
                .ToDictionary(p => p.s, p => p.f);

             var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

             return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }

in your example case You should use what Leppie has mentioned below (which I have upvoted)

<Func<TypeOflistElement,bool>>

Upvotes: 4

Novakov
Novakov

Reputation: 3095

Where method for IEnumerable<T> expects delegate for Func<T, bool> method, so GetLambdaExpression() must return Func<T, bool>

Where method for IQueryable<T> expects Expression<Func<T, bool>>, so GetLambdaExpression() must return Expression<Func<T, bool>>.

Expression can be converted to delegate by invoking Compile() method.

Upvotes: 0

Daniel
Daniel

Reputation: 632

You have to return Func<> since IEnumerable expects one, as in your example it would be:

 public Func<String,Bool> (string name){..}

Upvotes: 0

StuffHappens
StuffHappens

Reputation: 6557

You can return Func<bool, T> type like this

// Executed code
var filteredList = listWithNames.Where(GetLambdaExpression("Adam"));

// method
public Func<bool, ListElementTypeName> GetLambdaExpression(string name)
{
    return listElement => listElement.Name == name;
}

But I can't understand what exactly you are trying to do with it.

Upvotes: 0

leppie
leppie

Reputation: 117240

public Expression<Func<TypeOflistElement,bool>> GetLambdaExpression(string name)
{
    return listElement => listElement.Name == name;
}

Upvotes: 1

Related Questions