简体   繁体   English

如何在 C# 中的 foreach 循环中构建失败的电子邮件列表

[英]How to build list of failed emails in foreach loop in C#

I am trying to check Email validation for list of mails.我正在尝试检查邮件列表的电子邮件验证。 If any of the emails are invalid, i have to send the list of failed mail validations with false message, I am very new to C#, how can we achieve this?如果任何电子邮件无效,我必须发送带有错误消息的失败邮件验证列表,我对 C# 非常陌生,我们如何实现这一目标? when i am reading books i found it is possible through StringBuilder, but i am unable to find the syntax for this, can any please provide the syntax for this.当我阅读书籍时,我发现可以通过 StringBuilder 来实现,但是我找不到相关的语法,请提供相关的语法。

    public static string IsSMTPRequestValid(this SmtpGatewayRequest smtpRequest)
            {

                SmtpRequestContent content = smtpRequest.Body as SmtpRequestContent;

                foreach (string email in content.EmailCC)
                {
                    bool valid = IsEmail(email);
/* Here I would like to check in any of the mails are invalid I have to return false, with the list of invalid mails.*/
                }

            }

Thanks a lot in advance.非常感谢。

First you have to create instance of StringBuilder class and then just append all invalid emails to it in new lines.首先,您必须创建 StringBuilder 类的实例,然后将所有无效的电子邮件添加到新行中。 If you want to return all emails in string you have to call .ToString() method.如果要以字符串形式返回所有电子邮件,则必须调用.ToString()方法。

public static string IsSMTPRequestValid(this SmtpGatewayRequest smtpRequest)
{
    StringBuilder invalidEmails = new StringBuilder();
    SmtpRequestContent content = smtpRequest.Body as SmtpRequestContent;

    content.EmailCC.Where(email => !IsEmail(email))
        .ForEach(n =>
        {
            invalidEmails.AppendLine(n)
        });
    return invalidEmails.ToString();
}

or in easier-to-understand form或以更容易理解的形式

public static string IsSMTPRequestValid(this SmtpGatewayRequest smtpRequest)
{
    StringBuilder invalidEmails = new StringBuilder();
    SmtpRequestContent content = smtpRequest.Body as SmtpRequestContent;

    foreach (var email in content.EmailCC)
    {
        if (!IsEmail(email))
        {
            invalidEmails.AppendLine(email);
        }
    }

    return invalidEmails.ToString();
}

Moving away from this solutions i think that the best solution would be to return the entire list of items.远离这个解决方案,我认为最好的解决方案是返回整个项目列表。 For example:例如:

public static List<string> IsSMTPRequestValid(this SmtpGatewayRequest smtpRequest)
{
    List<string> invalidEmails = new List<string>();
    SmtpRequestContent content = smtpRequest.Body as SmtpRequestContent;

    foreach (var email in content.EmailCC)
    {
        if (!IsEmail(email))
        {
            invalidEmails.Add(email);
        }
    }

    return invalidEmails;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM