Fastest way to convert a list of strings into a single concatenated string?

后端 未结 7 2087
一向
一向 2021-02-14 21:27

I have some LINQ code that generates a list of strings, like this:

var data = from a in someOtherList
           orderby a
           select FunctionThatReturnsS         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 22:21

    Depending on how the JIT optimizes it, either string.Concat() or Marc's method with StringBuilder could be faster. Since you're using Linq here, I'll assume performance isn't the absolute #1 requirement, in which case I'd go with the easiest to read:

    string.Concat(data.ToArray());
    

    Edit: if and only if data is IEnumerable of a value type, you'll need to cast it to an IEnumerable:

    string.Concat(data.Cast().ToArray())
    
    
    

    Edit 2: I don't really mean Linq is slow. I only mean that the speed difference between the two ways I mentioned should be extremely minimal if even measurable.

    Edit 3: The JIT optimizes almost all operations on the String class, so the single call to the internal runtime of string.Concat really could be faster than using StringBuilder. I'm not sure it is, but you should test it to make sure.

    提交回复
    热议问题