Friday, April 29, 2011

Convert List to String

Sorry, todays silly question (and easy points) but whats the best way to convert a list(of string) to a string with the values seperated by ,

Sorry ....

From stackoverflow
  • String.Join(",", myListOfStrings.ToArray())
    
    spacemonkeys : ta blonde moment
  • That depends on what you mean by "best". The least memory intensive is to first calculate the size of the final string, then create a StringBuilder with that capacity and add the strings to it.

    The StringBuilder will create a string buffer with the correct size, and that buffer is what you get from the ToString method as a string. This means that there are no extra intermediate strings or arrays created.

    // specify the separator
    string separator = ", ";
    
    // calculate the final length
    int len = separator.Length * (list.Count - 1);
    foreach (string s in list) len += s.Length;
    
    // put the strings in a StringBuilder
    StringBuilder builder = new StringBuilder(len);
    builder.Append(list[0]);
    for (int i = 1; i < list.Count; i++) {
       builder.Append(separator).Append(list[i]);
    }
    
    // get the internal buffer as a string
    string result = builder.ToString();
    
    mquander : No matter what you mean by "best" this is probably not the best.
    Guffa : @mquander: It's the least memory intensive, I clearly stated that in the first paragraph. If you need to keep the memory load down, this is clearly the best method.
    Mehrdad Afshari : Not much difference in terms of memory intensiveness. There is no intermediate string in Join method. It's just the array of references.
    Meta-Knight : Profiling would give us the answer but I doubt there's a big enough difference to justify using this code instead of the one line String.Join.

0 comments:

Post a Comment