Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 313
jasonh Avatar asked Jul 14 '09 22:07

jasonh


3 Answers

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.

like image 84
Marc Gravell Avatar answered Nov 14 '22 07:11

Marc Gravell


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.

like image 27
JaredPar Avatar answered Nov 14 '22 09:11

JaredPar


Use "Aggregate" like this:

    List<string> strings = new List<string>() {"bob", "steve", "jane"};
    string result = strings.Aggregate((working, next) => working + next);
    Console.WriteLine(result);

Note: Aggregate is in the System.Linq namespace as an extension method.

like image 3
Mike Avatar answered Nov 14 '22 07:11

Mike