Alex Rivera | Logout

Appending a string in a loop in effective way

Asked 2011-07-09T23:03:13.563
12

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.

c#
Edit
Report

1 Answer

4

I like using the aggregate function in linq, such as:

string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
answered 2011-07-09T23:05:52.510

Your Answer