1

我需要帮助来最小化代码。我必须检查两个不同的机器,并且需要将它们存储在同一个 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);
}

帮助我避免多次重复代码。

4

3 回答 3

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);
}
于 2013-02-20T06:20:18.057 回答
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);
    }
于 2013-02-20T06:13:10.913 回答
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;
    }
于 2013-02-20T06:17:03.007 回答