Fastest way to convert a list of strings into a si

2019-03-26 18:22发布

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

var data = from a in someOtherList
           orderby a
           select FunctionThatReturnsString(a);

How do I convert that list of strings into one big concatenated string? Let's say that data has these entries:

"Some "
"resulting "
"data here."

I should end up with one string that looks like this:

"Some resulting data here."

How can I do this quickly? I thought about this:

StringBuilder sb = new StringBuilder();
data.ToList().ForEach(s => sb.Append(s));
string result = sb.ToString();

But that just doesn't seem right. If it is the right solution, how would I go about turning this into an extension method?

7条回答
Lonely孤独者°
2楼-- · 2019-03-26 18:37
data.ToList().Aggregate(new StringBuilder(), (sb, s) => sb.Append(s)).ToString();
查看更多
狗以群分
3楼-- · 2019-03-26 18:38

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<object>:

string.Concat(data.Cast<object>().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.

查看更多
【Aperson】
4楼-- · 2019-03-26 18:39

Alternative:

>>> data = ['Some ', 'resulting ', 'data here.']
>>> s = ''.join(data)
>>> s
'Some resulting data here.'
查看更多
走好不送
5楼-- · 2019-03-26 18:41

Have you tried String.Join? If you're already willing to take the overhead of a .ToList call then instead use .ToArray() and combine it with a call to String.Join.

var joined = String.Concat(someQuery.ToArray());

Note: My solution is likely not the fastest as it involves a bit of overhead in the array. My suspicion is that it would be faster to go more Marc's route. But in most cases if you're just looking for the quick and dirty way to do it in code, my route will work.

查看更多
疯言疯语
6楼-- · 2019-03-26 18:53

You can use this statement. String.Join("",someOtherList);

查看更多
Rolldiameter
7楼-- · 2019-03-26 18:54

How about:

public static string Concat(this IEnumerable<string> source) {
    StringBuilder sb = new StringBuilder();
    foreach(string s in source) {
        sb.Append(s);
    }
    return sb.ToString();
}

and:

string s = data.Concat();

This then has no need for the extra ToList() / ToArray() step.

查看更多
登录 后发表回答