String.Join非字符串数组的最佳方法是什么?

时间:2010-07-06 15:08:54

标签: c# string arrays join

String.Join非字符串数组的简写方法是什么?如第二个例子所示?

string[] names = { "Joe", "Roger", "John" };
Console.WriteLine("the names are {0}", String.Join(", ", names)); //ok

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m };
Console.WriteLine("the prices are {0}", String.Join(", ", prices)); //bad overload

5 个答案:

答案 0 :(得分:13)

如果你有LINQ

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.WriteLine("the prices are {0}", 
    String.Join(", ", 
       prices.Select(p => p.ToString()).ToArray()
    )
);

答案 1 :(得分:4)

Console.WriteLine("the prices are {0}", String.Join(", ", Array.ConvertAll(prices, p => p.ToString()));

答案 2 :(得分:2)

我有两个Delimit函数可以帮我这么做 它们的占用空间非常小,因为没有创建第二个数组,并且在返回字符串的地方,StringBuilder在封面下使用,因此它不会复制并连接到相同的字符串,导致连接延迟更长。
因此,它们可用于一系列非常大和/或未知的长度。

frist写入TextWriter并且不返回任何内容,第二个返回一个字符串,并委托第一个传入StringWriter。

public static void Delimit<T>(this IEnumerable<T> me, System.IO.TextWriter writer, string delimiter)
{
    var iter = me.GetEnumerator();
    if (iter.MoveNext())
        writer.Write(iter.Current.ToString());

    while (iter.MoveNext())
    {
        writer.Write(delimiter);
        writer.Write(iter.Current.ToString());
    }
}

public static string Delimit<T>(this IEnumerable<T> me, string delimiter)
{
    var writer = new System.IO.StringWriter();
    me.Delimit(writer, delimiter);
    return writer.ToString();
}

所以给定的价格高于你的价格

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.WriteLine("the prices are {0}", prices.Delimit(", "));

decimal[] prices = { 39.99M, 29.99m, 29.99m, 19.99m, 49.99m }; 
Console.Write("the prices are ")
prices.Delimit(System.Console.Out, ", ");
Console.WriteLine();

答案 3 :(得分:1)

ck停止的地方捡起,将其提取到方法以使其可重复使用:

public static class EnumerableExtensions {
  public static string Join<T>(this IEnumerable<T> self, string separator) { 
    if (self == null) throw new ArgumentNullException();
    if (separator == null) throw new ArgumentNullException("separator");
    return String.Join(separator, self.Select(e => e.ToString()).ToArray());
  }
}

现在用法更具可读性:

Console.WriteLine("the prices are {0}", prices.Join(", "));

答案 4 :(得分:0)

可以使用linq转换为字符串:

Console.WriteLine("the prices are {0}", String.Join(", ", prices.Select(p => p.ToString()).ToArray()));

或使用Aggregate()而不是string.Join()

Console.WriteLine("the prices are {0}",
    prices.Select(p => p.ToString()).
          .Aggregate((total, p) => total + ", " + p));

或甚至(格式略有不同)

Console.WriteLine(
    prices.Select(p => p.ToString()).
          .Aggregate("the prices are", (total, p) => total + ", " + p));