Search code examples
c#.netlinqlinq-to-sqllinq-to-entities

Add a if statement condition to a Linq statement


I am wanting a nice clean approach to adding in a conditional to an existing linq statement . I have a NEW variable personContactRoleId which will be zero or not zero.

context.PersonContactRoles
          .Where(pcr => pcr.PersonId == personId);                        
          .ToList()
          .ForEach(pcr =>
          {
              // a lot of code
          }

I was able to solve it with the iqueryable deferment of execution using an if statement, but it seems rather ugly and possibly less performant? Anything better to use?

var query = context.PersonContactRoles
          .Where(pcr => pcr.PersonId == personId);                        

if(personContactRoleId != 0)
{
    query = query.Where(b => b.PersonContactRoleId == personContactRoleId);
}

var results = query.ToList();
results.ForEach(pcr =>
{
    // a lot of code
}

Again, this works, but looking for a cleaner way of doing this


Solution

  • The solution you have is fine, but if you want to put it all into one query without an if, you can add an additional Where condition that returns records where either personContactRoleId == 0 or prc.PersonContactRoleId == personContactRoleId is true:

    context.PersonContactRoles
        .Where(pcr =>
            pcr.PersonId == personId &&
            (personContactRoleId == 0 || pcr.PersonContactRoleId == personContactRoleId))
        .ToList()
        .ForEach(pcr =>
        {
            // a lot of code
        });