将字符串列表转换为单个串联字符串的最快方法? [英] Fastest way to convert a list of strings into a single concatenated string?

查看:124
本文介绍了将字符串列表转换为单个串联字符串的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些LINQ代码生成一个字符串列表,像这样:

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?

推荐答案

怎么样:

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

和:

string s = data.Concat();

这样就不需要执行额外的ToList()/ToArray()步骤.

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

这篇关于将字符串列表转换为单个串联字符串的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆