Appending a string in a loop in effective way

前端 未结 5 2180
孤城傲影
孤城傲影 2020-12-05 21:15

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

相关标签:
5条回答
  • 2020-12-05 21:50

    For your final pipe issue, simply leave the last append outside of the loop

    int size = EmployeeList.length()
    for(int i = 0; i < size - 1; i++)
    {
         final+=EmployeeList.getEmployee(i).Name+"|";
    }
    final+=EmployeeList.getEmployee(size-1).Name;
    
    0 讨论(0)
  • 2020-12-05 21:53

    You should join your strings.

    Example (borrowed from MSDN):

    using System;
    
    class Sample {
        public static void Main() {
        String[] val = {"apple", "orange", "grape", "pear"};
        String sep   = ", ";
        String result;
    
        Console.WriteLine("sep = '{0}'", sep);
        Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
        result = String.Join(sep, val, 1, 2);
        Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 21:58

    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.

    0 讨论(0)
  • 2020-12-05 21:59

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

    string[] words = { "one", "two", "three" };
    var res = words.Aggregate((current, next) => current + ", " + next);
    
    0 讨论(0)
  • 2020-12-05 22:07

    For building up like this, a StringBuilder is probably a better choice.

    0 讨论(0)
提交回复
热议问题