crystyxn
crystyxn

Reputation: 1611

Concatenating string from a list of strings

I have a list of strings and I am trying to concatenate it so its one bigger string.

foreach (var item in dir3)
     {
           resultDirectionHtml = string.Join(",",item.html_instructions);
     }


await EmailSent(resultDirectionHtml);

What happens currently is it sends only the last element of the list. How can I make it so it concatenates all 8 or so strings and then sends it ??

Upvotes: 0

Views: 96

Answers (4)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

I would do something like this:

using System.Text;
var builder = new StringBuilder();

foreach (var item in dir3)
     {
           builder.Append(item.html_instructions);
           builder.Append("<br />");
     }

resultDirectionHtml = builder.ToString();

Every time you "add" to a string, it creates a new string in memory so you end up with as many strings as many items you have in that list and you keep eating away at the memory. it is highly recommended to not use such code in a loop.

5 or more items I would use a StringBuilder. Anything less, probably not worth it.

Upvotes: 5

S.N
S.N

Reputation: 5140

Your code reassign the value of resultDirectionHtml on every iteration and hence you see only the last value. use += instead of =

foreach (var item in dir3)
     {
           resultDirectionHtml += string.Join(",",item.html_instructions);
     }

On a different note, if you fancy using LINQ then you could easily write like below with the help of Aggregate extension.

string[] words = { "a", "aa", "aaa" };
var output = words.Aggregate((current, next) => current + ", " + next);
//The value of output will be  a, aa, aaa

Upvotes: 1

Travis J
Travis J

Reputation: 82337

You could use a projection instead of the foreach loop

resultDirectionHtml += string.Join(",",dir3.Select(i => i.html_instructions));

Upvotes: 2

nbokmans
nbokmans

Reputation: 5757

Use += instead of just =. Currently you are reassigning the entire string every loop iteration, instead of appending to it.

So your code becomes:

foreach (var item in dir3)
     {
           resultDirectionHtml += string.Join(",",item.html_instructions);
     }


await EmailSent(resultDirectionHtml);

Upvotes: 3

Related Questions