I have an array of valid e-mail address domains. Given an e-mail address, I want to see if its domain is valid
string[] validDomains = { "@test1.com", "@test2.com", "@test3.com" };
string email = "[email protected]"
Is there a way to check if email
contains any of the values of validDomains
without using a loop?
I would like to recommend you the following code:
HashSet<string> validDomains = new HashSet<string>
{
"test1.com", "test2.com", "test3.com"
};
const string email = "[email protected]";
MailAddress mailAddress = new MailAddress(email);
if (validDomains.Contains(mailAddress.Host))
{
// Contains!
}
HashSet.Contains Method is an O(1) operation; while array - O(n). So HashSet<T>.Contains
is extremely fast. Also, HashSet
does not store the duplicate values and there is no point to store them in your case.
MailAddress Class represents the address of an electronic mail sender or recipient. It contains mail address parsing logic (just not to reinvent the wheel).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With