Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a string in a loop in effective way

Tags:

c#

for long time , I always append a string in the following way.

for example if i want to get all the employee names separated by some symbol , in the below example i opeted for pipe symbol.

string final=string.Empty;

foreach(Employee emp in EmployeeList)
{
  final+=emp.Name+"|"; // if i want to separate them by pipe symbol
}

at the end i do a substring and remove the last pipe symbol as it is not required

final=final.Substring(0,final.length-1);

Is there any effective way of doing this.

I don't want to appened the pipe symbol for the last item and do a substring again.

like image 566
kobe Avatar asked Jul 09 '11 23:07

kobe


1 Answers

Use string.Join() and a Linq projection with Select() instead:

finalString = string.Join("|", EmployeeList.Select( x=> x.Name));

Three reasons why this approach is better:

  1. It is much more concise and readable – it expresses intend, not how you want to achieve your goal (in your
    case concatenating strings in a loop). Using a simple projection with Linq also helps here.

  2. It is optimized by the framework for performance: In most cases string.Join() will use a StringBuilder internally, so you are not creating multiple strings that are then un-referenced and must be garbage collected. Also see: Do not concatenate strings inside loops

  3. You don’t have to worry about special cases. string.Join() automatically handles the case of the “last item” after which you do not want another separator, again this simplifies your code and makes it less error prone.

like image 63
BrokenGlass Avatar answered Sep 19 '22 13:09

BrokenGlass