Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
449 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...