1

How can i Chain EF queries with OR condition

Right now i am chaining or building the query like below and this is ended up adding AND conditions

              if (model.EMailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail)
                                        );
                }

                if (model.MailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPMail)
                                    );
                }

                if (model.PhoneChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)
                                    );
                }

How can we add OR conditions to this chain

Sebastian
  • 4,625
  • 17
  • 76
  • 145
  • OR means you need only one of the items so you can put a return after each item so you do not need to check the rest of the items. – jdweng Feb 07 '22 at 16:47
  • @jdweng I want to make the query as EmailChoice.Contains(SELECTEDVALUES) OR PhoneChoice.Contains(SELECTEDVALUES) OR MailChoice.Contains(SELECTEDVALUES) The SELECTEDVALUES can be Null or not and that is the reason why checking for counts – Sebastian Feb 07 '22 at 16:54
  • What I mean is if EmailChoice is true (or count is > 0) you do not need to check the other items and can return. – jdweng Feb 07 '22 at 16:57

1 Answers1

2
bool anyEmails = model.EMailChoices?.Any() == true;
bool anyMails = model.MailChoices?.Any() == true;
bool anyPhones = model.PhoneChoices?.Any() == true;

if(anyEmails || anyMails || anyPhones)
{
     query = query.Where( 
         c => (anyEmails && model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyMails && model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyPhones && model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)));
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Might be offtopic but https://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0 suggests stick with Any for IEnumerable and for List count is better to use – Sebastian Feb 07 '22 at 17:00