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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With