写老派最有效的方法是什么:

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吗?


当前回答

我之前写过一篇博客,我所做的正是你想要的:

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方式”,你可能是在谈论LINQ通过使用扩展方法使函数式编程变得更容易接受的方式。我的意思是,允许函数以视觉上的线性方式(一个接一个)链接而不是嵌套(一个在另一个中)的语法糖。例如:

int totalEven = Enumerable.Sum(Enumerable.Where(myInts, i => i % 2 == 0));

可以这样写:

int totalEven = myInts.Where(i => i % 2 == 0).Sum();

可以看出第二个例子更容易阅读。您还可以看到如何添加更多的函数,同时减少缩进问题或出现在表达式末尾的Lispy闭括号。

很多其他答案都说字符串。Join是正确的方法,因为它是最快或最简单的阅读方式。但如果你接受我对“超级酷的LINQ方式”的解释,那么答案是使用字符串。连接,但要将它包装在LINQ风格的扩展方法中,这将允许您以一种视觉上令人愉悦的方式连接函数。如果你想写sa。Concatenate(", ")你只需要创建这样的东西:

public static class EnumerableStringExtensions
{
   public static string Concatenate(this IEnumerable<string> strings, string separator)
   {
      return String.Join(separator, strings);
   }
}

这将提供与直接调用一样的性能代码(至少在算法复杂性方面),并且在某些情况下可能使代码更具可读性(取决于上下文),特别是当块中的其他代码使用链式函数样式时。

我对字符串进行了基准测试。使用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

阵列越大,间隔越大

您看过聚合扩展方法了吗?

var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);

为什么使用Linq?

string[] s = {"foo", "bar", "baz"};
Console.WriteLine(String.Join(", ", s));

这是完美的工作,并接受任何IEnumerable<string>,据我所知。不需要在这里聚合任何东西,这是非常慢的。

我之前写过一篇博客,我所做的正是你想要的:

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(", ");