写老派的最有效方法是什么:
StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
foreach (string s in strings)
{
sb.Append(s + ", ");
}
sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();
...在 LINQ 中?
最佳答案
此答案显示了问题中要求的 LINQ ( Aggregate
) 的用法,不适合日常使用。因为这不使用 StringBuilder
它对于很长的序列会有可怕的性能。对于常规代码,请使用 String.Join
,如其他 answer 所示
使用这样的聚合查询:
string[] words = { "one", "two", "three" };
var res = words.Aggregate(
"", // start with empty string to handle empty list case.
(current, next) => current + ", " + next);
Console.WriteLine(res);
这输出:
, one, two, three
An aggregate is a function that takes a collection of values and returns a scalar value. Examples from T-SQL include min, max, and sum. Both VB and C# have support for aggregates. Both VB and C# support aggregates as extension methods. Using the dot-notation, one simply calls a method on an IEnumerable object.
Remember that aggregate queries are executed immediately.
More information - MSDN: Aggregate Queries
If you really want to use Aggregate
use variant using StringBuilder
proposed in comment by CodeMonkeyKing which would be about the same code as regular String.Join
including good performance for large number of objects:
var res = words.Aggregate(
new StringBuilder(),
(current, next) => current.Append(current.Length == 0? "" : ", ").Append(next))
.ToString();
关于c# - 使用 LINQ 连接字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/217805/