Search code examples
c#listlambdapredicate

C# Is there a way to use a list in a TrueForAll List method


I have a helper method that is determining if a list of email addresses match certain email domains that the application says are acceptable. The method looks like this:

public bool IsValidEmail(List<string> emails)
{
     return emails.TrueForAll(x => x.contains("gmail.com") || x.contains("hotmail.com") || x.contains("yahoo.com")
}

This works fine of course, but I'm wondering if to get rid of magic strings there is a way to have a list like

 var validEmailDomains = new List<string> {"gmail.com", "hotmail.com", "yahoo.com"}

and use this in the Predicate that is used in TrueForAll?


Solution

  • You can use LINQ's All :

    return emails.TrueForAll(x=>validDomains.Any(d=>x.Contains(d)));
    

    or

    return emails.All(x=>validDomains.Any(d=>x.Contains(d)));
    

    All does for all IEnumerable<T>'s what TrueForAll did only for List