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?
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:
Edit: if and only if data is IEnumerable of a value type, you'll need to cast it to an IEnumerable<object>:
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.
Alternative:
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.
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.
You can use this statement. String.Join("",someOtherList);
How about:
and:
This then has no need for the extra
ToList()
/ToArray()
step.