2015-12-22 67 views
1

我想创建一个HTML电子邮件模板与C#中的表。对于我使用的字符串,并试图连接HTML标签。现在,我必须从列表中的表数据添加值,但不能添加字符串..Below里面的foreach循环是我的代码..如何在c#中的字符串中使用foreach?

EmailFormat += "<table><thead><tr><th>FirstName</th><th>LastName</th><th>Id</th><th>Date</th></thead>" 
+ foreach(Notification pReview in Review) 
    { 

    } 
+ "</table>"; 

我怎样才能做到这一点?

回答

3

foreach声明,而不是一个表达。您不能在表达式中使用语句。

这相当容易,虽然解决:

EmailFormat += "<table><thead><tr><th>FirstName</th><th>LastName</th><th>Id</th><th>Date</th></thead>"; 
foreach(Notification pReview in Review) 
{ 
    EmailFormat += /*anything you want to add...*/; 
} 
EmailFormat += "</table>"; 

或者更好的是,使用StringBuilder来构建你的字符串。

+0

另请注意,在.Net 4.5或更高版本中,您可以使用[String.Concat (IEnumerable )](https://msdn.microsoft.com/en-us/library/dd991828%28v=vs.110% 29.aspx)连接所有的'pReview.ToString()'值,而不是明确地使用'foreach'。 –

+0

@MatthewWatson - 目前尚不清楚*什么*被连接,但我想象它涉及实例属性和静态字符串的组合(以生成表格行标记)。它猜测使用'StringBuilder.AppendFormat'来执行这个任务比将'pReviews'映射到字符串更清晰。 – Amit

+1

当然,我只是说,如果他们*正在执行EmailFormat + = Review;那么他们可以使用'string.Concat()' –

1

使用StringBuilder与他的方法追加。这种方式,您可以建立在部分字符串瑟例如here

2

试试这个

EmailFormat += "<table><thead><tr><th>FirstName</th><th>LastName</th><th>Id</th><th>Date</th></thead>" + string.Concat(Review.Select(_ => _.{Anything})) + "</table>"; 
2

可以使用StringBuilder完成同样的任务,因为它更好地串联时,字符串。 例如

 StringBuilder EmailFormat = new StringBuilder(); 
     EmailFormat.Append("<table><thead><tr><th>FirstName</th><th>LastName</th><th>Id</th><th>Date</th></thead>"); 
     foreach (Notification pReview in Review) 
     { 
      EmailFormat.Append("<tr><td>pReview.FirstName</td><td>pReview.LastName</td><td>pReview.Date</td></tr>"); 
     } 
     EmailFormat.Append("</table>"); 

然后转换EmailFormat为字符串以供进一步使用。