写老派最有效的方法是什么:
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吗?
写老派最有效的方法是什么:
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吗?
当前回答
您看过聚合扩展方法了吗?
var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);
其他回答
我对字符串进行了基准测试。使用BDN在15个字符串数组上Join vs .Aggregate:
Method | Mean | Error | StdDev | Gen0 | Allocated |
---|---|---|---|---|---|
String_Join | 92.99 ns | 9.905 ns | 0.543 ns | 0.0560 | 352 B |
LING_Aggregate | 406.00 ns | 74.662 ns | 4.092 ns | 0.4640 | 2912 B |
阵列越大,间隔越大
我之前写过一篇博客,我所做的正是你想要的:
http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html
在博客文章中描述了如何实现工作在IEnumerable上的扩展方法,并命名为Concatenate,这将允许您编写如下内容:
var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();
或者更复杂的事情,比如:
var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");
这里有很多选择。你可以使用LINQ和StringBuilder,这样你就可以得到这样的性能:
StringBuilder builder = new StringBuilder();
List<string> MyList = new List<string>() {"one","two","three"};
MyList.ForEach(w => builder.Append(builder.Length > 0 ? ", " + w : w));
return builder.ToString();
你可以在聚合中使用StringBuilder:
List<string> strings = new List<string>() { "one", "two", "three" };
StringBuilder sb = strings
.Select(s => s)
.Aggregate(new StringBuilder(), (ag, n) => ag.Append(n).Append(", "));
if (sb.Length > 0) { sb.Remove(sb.Length - 2, 2); }
Console.WriteLine(sb.ToString());
(选择在那里只是为了显示你可以做更多的LINQ的东西。)
return string.Join(", ", strings.ToArray());
在。net 4中,有一个新的重载字符串。接受IEnumerable<string>的连接。代码将如下所示:
return string.Join(", ", strings);