C# 字符串列表到一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/318756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:00:03  来源:igfitidea点击:

List of strings to one string

c#stringperformancefunctional-programming

提问by maxfridbe

Lets say you have a:

假设你有一个:

List<string> los = new List<string>();

In this crazy functional world we live in these days which one of these would be best for creating one string by concatenating these:

在这个疯狂的函数世界中,我们生活在这些天,其中之一最适合通过连接这些来创建一个字符串:

String.Join(String.Empty, los.ToArray());

StringBuilder builder = new StringBuilder();
los.ForEach(s => builder.Append(s));

string disp = los.Aggregate<string>((a, b) => a + b);

or Plain old StringBuilder foreach

或普通的旧 StringBuilder foreach

OR is there a better way?

或者,还有更好的方法?

回答by BFree

I would go with option A:

我会选择A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

我的推理是因为 Join 方法是为此目的编写的。事实上,如果你查看 Reflector,你会发现不安全的代码被用来真正优化它。另外两个也有效,但我认为 Join 函数是为此目的编写的,我猜是最有效的。虽然我可能是错的...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

根据@Nuri YILMAZ 没有.ToArray(),但这是 .NET 4+:

String.Join(String.Empty, los);

回答by Tom Ritter

My vote is string.Join

我的投票是字符串。加入

No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.

不需要创建 lambda 评估和临时函数,更少的函数调用,更少的堆栈推送和弹出。

回答by J Cooper

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

String.Join() 的实现速度非常快,而且由于您已经有了相关字符串的集合,这可能是最佳选择。最重要的是,它大喊“我正在加入一个字符串列表!” 总是很好。

回答by Pent Ploompuu

string.Concat(los.ToArray());

If you just want to concatenate the strings then use string.Concat() instead of string.Join().

如果您只想连接字符串,请使用 string.Concat() 而不是 string.Join()。

回答by mnieto

If you use .net 4.0 you can use a sorter way:

如果您使用 .net 4.0,您可以使用排序器方式:

String.Join<string>(String.Empty, los);

回答by landrady

los.Aggregate((current, next) => current + "," + next);