使用LINQ/lambdas构建内部异常消息的逗号分隔字符串

本文关键字:分隔 字符串 消息 异常 LINQ lambdas 构建 内部 使用 | 更新日期: 2023-09-27 18:21:16

SmtpFailedRecipientsException.InnerExceptionsSmtpFailedRecipientException的数组。我想构建一个字符串,看起来像:

"下列收件人失败:[joe@domain1.com,steve@domain2.com]。电子邮件已发送给所有其他收件人成功地"

SmtpFailedRecipientException.FailedRecipient保存电子邮件地址。

我想知道是否有一种方法可以使用LINQ和/或lambda函数在这个数组上有效地执行join,也许可以通过读取SmtpFailedRecipientException.Message或类似的内容将其转换为string[],而不是为循环编写C样式?

此问题(从InnerException获取所有消息?)解决了层次嵌套异常的更常见情况,但这不是我所追求的。。。那里的asnwer比我需要的要复杂得多(正如这里的答案所示)。

使用LINQ/lambdas构建内部异常消息的逗号分隔字符串

string[] exceptionMessages = yourSmtpFailedRecipientsException.InnerExceptions
    .Select(ex => ex.Message)
    .ToArray();

如果你想以逗号分隔输出,你可以使用String.Join:

Console.Write(String.Join(",", exceptionMessages));

您感兴趣的属性是SmtpFailedRecipientException.FailedRecipient属性,根据文档"指示有传递困难的电子邮件地址"。

要获得失败地址的列表,您可以执行以下操作:

IEnumerable<string> emailAddresses = SmtpFailedRecipientsException.InnerExceptions.Select(x=>x.FailedRecipient);
string joinedAddresses = String.Join(", ", emailAddresses);
string message = String.Format("The following recipients failed: [{0}]. The email was sent to all other recipients succesfully", joinedAddresses );

这使用了一些局部变量,如果你愿意的话,你可以跳过它们,我使用它们主要是为了可读性,让它清楚地表明我在做什么。