【问题标题】:Displaying a list of string in a string在字符串中显示字符串列表
【发布时间】:2016-01-29 18:46:20
【问题描述】:

好的,我在这里尝试向用户发送有关无效附件的电子邮件。我在前一个函数中收集了一个无效附件名称(字符串)列表,然后我尝试发送一封电子邮件,其中列出了所有被认为无效的附件。不知道如何处理这种情况。我有下面的例子

List<string> invalidType = new List<string>();

if (invalidType != null)
{
    emailInvalidBody = new ItemBody
    {
        Content = " Expense attachements recieved with subject line [ "
           + email.Subject 
           + " ] sent at  [  " 
           + email.DateTimeReceived.Value.DateTime.ToLocalTime() 
           + " ] had the following invalid attachments [" 
           + invalidType 
           + "].  Please make sure all attachment's are images or PDF's.",
    };
}
List<Recipient> emailInvalidRecipients = new List<Recipient>();
emailInvalidRecipients.Add(new Recipient
{
    EmailAddress = new EmailAddress
    {
        Address = email.Sender.EmailAddress.Address
    }
});
Message invalidEmailMessage = new Message
{
    Subject = "Invalid Expenses",
    Body = emailInvalidBody,
    ToRecipients = emailInvalidRecipients
};
starBox.Users[EMAILBOX].SendMailAsync(invalidEmailMessage, false).Wait();

我的最终目标是拥有一个可以执行以下操作的电子邮件正文

“在 2016 年 1 月 29 日 8:00 发送的主题行主题收到的费用附件包含以下无效附件 [ invalidattachment1 invalidattachment2 invalidattachment3 invalidattachment4 ]。请确保所有附件都是图像或 PDF 的。”,

【问题讨论】:

  • 看起来您在连接在一起并分配给Content 的某些字符串之前缺少@,或者应该全部放在一行上?
  • 为了完整性(并避免不必要的和奇怪的电子邮件),您还应该在检查 != null; 后检查 invalidType.Any()奖励:非编程观察:你拼错了“附件”和“收到”
  • 哈哈谢谢你,写这篇文章

标签: c# string counter


【解决方案1】:

使用 string.Join 将您的List&lt;string&gt; 转换为一个列表,其中所有项目都连接在一起

List<string> invalidType = new List<string>();
.....

// Probably you don't need to check for null but for element count.
// However it doesn't hurt to be a little defensive...
if (invalidType != null && invalidType.Count > 0)
{
    string attachments = string.join(",", invalidType);
    emailInvalidBody = new ItemBody
    {
        Content = " Expense attachments received with subject line [ " + 
                  email.Subject + " ] sent at  [  " + 
                  email.DateTimeReceived.Value.DateTime.ToLocalTime() + 
                  " ]  had the following invalid attachments [" + 
                  attachments + "].  Please make sure all " + 
                  " attachment's are images or PDF's.",
    };

}

【讨论】:

  • 这比LingAggregate() 方法更有效。 +1 (y)
【解决方案2】:

你可以使用LinqAggregate

Content = " Expense attachements recieved with subject line [ " +
 email.Subject + " ] sent at  [  " + 
email.DateTimeReceived.Value.DateTime.ToLocalTime() + 
" ]had the following invalid attachments [" 
+ invalidType.Aggregate((i, j) => i + " " + j))
+ "].  Please make sure all attachment's are images or PDF's.",

【讨论】:

  • true,但意图不像 string.Join() 那样清晰
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多