Mike Flynn
Mike Flynn

Reputation: 24325

Converting Lambda Functions into Lambda Expression

I am trying to combine a multiple selection with a lambda function into an lambda expression. How do I do that? I know the last line is wrong, but giving you an idea of what I mean.

Func<Event, bool> where = null;

if (!string.IsNullOrWhiteSpace(searchToken))
    where = q => q.Name.ToUpper().Contains(searchToken.ToUpper());

where += q => q.Hidden = false;

Expression<Func<Event, bool>> where1 = q => where; <-- Erroring

Upvotes: 1

Views: 442

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

I suspect you want PredicateBuilder. (The source is available on that page.) You'd use it like this:

var predicate = q => !q.Hidden;
if (!string.IsNullOrWhiteSpace(searchToken))
{
    predicate = predicate.And(q => q.Name.ToUpper()
                                         .Contains(searchToken.ToUpper());
}
return predicate;

That's assuming you want to "and" the conditions - you never made that clear...

Note that that is not a good way to compare in a case-insensitive way, either. If you could tell us what's going to consume the query (e.g. LINQ to SQL, LINQ to EF) we could suggest a provider-compatible way of performing a case-insensitive query.

Upvotes: 4

pero
pero

Reputation: 4259

Look at http://msdn.microsoft.com/en-us/library/bb882637.aspx. How to use expression trees to build dynamic queries.

AFAIK when using Expression <> like that the expression must be known in compile time, because the compiler then build AST abstract syntax three and stores it as data in your Expression <> instance.

Upvotes: 0

Related Questions