2

I am trying to create a HTML Email Template with table in c# . For the same i used string and trying to concatenate the HTML tags. Now i have to add values from List as table data but not able to add the foreach loop inside string ..Below is my code..

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

   }
+ "</table>";

How can I do this?

4 Answers 4

3

foreach is a Statement, not an Expression. You can't use statements inside expressions.

It' fairly easy to solve though:

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>";

Or better yet, use a StringBuilder to construct your string.

Sign up to request clarification or add additional context in comments.

3 Comments

Also note that in .Net 4.5 or later you can use String.Concat<T>(IEnumerable<T>) to concatenate all the pReview.ToString() values rather than explicitly using foreach.
@MatthewWatson - It's not clear what is being concatenated but I'd imagine it involves a combination of instance properties and static string (to generate table rows markup). It guess it would be cleaner to use StringBuilder.AppendFormat for this task vs. mapping pReviews to strings.
Of course; I just meant that if they were doing EmailFormat += Review; then they could use string.Concat()
2

Try this

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

Comments

2

You can use StringBuilder for the same task, as its better when concatenating strings. For example

        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>");

Then Convert EmailFormat to String for further use.

Comments

1

Use a StringBuilder with his method append. this way you can build the string in parts se example here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.