Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

c# - Appending a string in a loop in effective way

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...