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条回答
干净又极端
2楼-- · 2019-03-26 18:58

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.

查看更多
登录 后发表回答