Reputation: 317
I need help in minimizing the code. I have to check two different maches and need to store both in the same matchcollection. I dont know how to do, here is my code, can any one help me to do so please.
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
MatchCollection emailCollection1;
//Get emails from ResponsibleConsultant
emailCollection1 = Regex.Matches(piWorkitem.ResponsibleConsultant, patternEmail);
foreach (Match mail in emailCollection1.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
MatchCollection emailCollection2;
//Get emails from ResponsibleConsultant
emailCollection2 = Regex.Matches(piWorkitem.SupplierConsultant, patternEmail);
foreach (Match mail in emailCollection2.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
Help me to do avoid the repeating the code more than once.
Upvotes: 1
Views: 762
Reputation: 317
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var allInput = piWorkitem.ResponsibleConsultant + " " + piWorkitem.SupplierConsultant;
var emailCollection = Regex.Matches(allInput , patternEmail);
foreach (Match mail in emailCollection.Cast<Match>().Where(mail => emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
Upvotes: 2
Reputation: 1
private void TestFunc()
{
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var all = ExtactMatches(patternEmail, piWorkitem.SupplierConsultant, piWorkitem.ResponsibleConsultant);
}
private IEnumerable<string> ExtactMatches(string pattern, params string[] srcText)
{
HashSet<string> emailaddresses = new HashSet<string>();
foreach (var text in srcText)
{
//Get emails from ResponsibleConsultant
var emailCollection1 = Regex.Matches(text, pattern);
foreach (Match mail in emailCollection1.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString(CultureInfo.InvariantCulture))))
{
emailaddresses.Add(mail.Value);
}
}
return emailaddresses;
}
Upvotes: 0
Reputation: 18569
You can join both of the result using Union
Try this :
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var emailCollection1 = Regex.Matches(piWorkitem.ResponsibleConsultant, patternEmail).Cast<Match>().Union(Regex.Matches(piWorkitem.SupplierConsultant, patternEmail).Cast<Match>());
foreach (Match mail in emailCollection1.Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
Upvotes: 0