Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string contains an array of values?

Tags:

c#

.net

email

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?

like image 400
Steven Avatar asked Aug 14 '12 18:08

Steven


1 Answers

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).

like image 63
Sergey Vyacheslavovich Brunov Avatar answered Sep 18 '22 20:09

Sergey Vyacheslavovich Brunov