Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use LINQ’s All :

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

or

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading