Garry A
Garry A

Reputation: 465

Combining two expressions

I have an Expression<func<Portfolio, bool>> and I want to add an extra condition if an expression is true, here is my code,

Expression<Func<Portfolio, bool>> condition = x =>
        x.Client == Params.Client
        && x.AnalysisDate == Params.AnalysisDate
        && x.AsOf <= Params.ReportDate

    if (Params.Names.Any())
    {
        //Here I want to add an extra condition to add the following to the condition
       && portfoliosParams.Names.Contains(x.Name);
    }

Any ideas?

Upvotes: 1

Views: 60

Answers (1)

Orace
Orace

Reputation: 8359

If Params.Names.Any() (shouldn't it be portfoliosParams.Names.Any() ?) is evaluated before you build the expression, the easiest way to achieve this is probably like so :

Expression<Func<Portfolio, bool>> condition;

if (Params.Names.Any())
{
    condition = x => x.Client == Params.Client &&
                     x.AnalysisDate == Params.AnalysisDate &&
                     x.AsOf <= Params.ReportDate &&
                     portfoliosParams.Names.Contains(x.Name);
}
else
{
    condition = x => x.Client == Params.Client &&
                     x.AnalysisDate == Params.AnalysisDate &&
                     x.AsOf <= Params.ReportDate;
}

Otherwise you should include the condition in the expression:

Expression<Func<Portfolio, bool>> condition = x =>
    x.Client == Params.Client &&
    x.AnalysisDate == Params.AnalysisDate &&
    x.AsOf <= Params.ReportDate &&
    (Params.Names.Count() == 0 || portfoliosParams.Names.Contains(x.Name));

Finally is you really need to build up the expression, there is already answers about expression combination.

Upvotes: 1

Related Questions