Stringbuilder 从多个数组追加表单

Stringbuilder append form from multiple arrays

我有一个 StringBuilder,我正在尝试从多个列表中附加参数,如下所示:

var sb = new StringBuilder();
var list1 = new List<string>() { "a", "b", "c" }
var list2 = new List<string>() { "d", "e" }
sb.AppendFormat(" {0}, {1}, {2}, {3}, {4} ", list1, list2);

我得到一个例外:

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

我所做的就是创建一个临时列表

var temp = new List<string>();
temp.AddRange(list1);
temp.AddRange(list2);
sb.AppendFormat(" {0}, {1} ,{2}  ,{3}  ,{4} ", new List().Add);

有没有更优雅的方法来做到这一点?

试试这个:

var sb = new StringBuilder();
var list1 = new List<string>() {"a", "b", "c"};
var list2 = new List<string>() {"d", "e"};
sb.AppendFormat(" {0}, {1}, {2}, {3}, {4} ", list1.Concat(list2).ToArray());
Console.WriteLine(sb.ToString());

您可以像这样简单地做一些事情:

var result = string.Join(",", list1.Concat(list2));

您可以像这样将其附加到字符串生成器:

sb.Append(result);