2013-02-20 43 views
1

我需要幫助最小化代碼。我必須檢查兩個不同的maches,並且需要將它們存儲在同一個matchcollection中。我不知道該怎麼做,這裏是我的代碼,請任何人都幫助我這麼做。如何創建matchcollection數組

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); 
} 

幫助我避免重複代碼不止一次。

+2

使包含邏輯函數,然後重新使用該功能。 – Raptor 2013-02-20 06:04:46

回答

2
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); 
} 
+0

你讓我的工作變得非常簡單,非常感謝 – user1845163 2013-02-20 06:26:37

0

你可以加入這兩種使用Union

試試這個結果:

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); 
    } 
+0

非常感謝你 – user1845163 2013-02-20 06:27:04

0
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; 
    } 
+0

非常感謝你 – user1845163 2013-02-20 06:42:29