在括号 C# 中打印列表

时间:2021-07-02 08:52:20

标签: c# list

到目前为止我发现的最好的结果是这个

List<int> pL = new List<int> { 1, 3, 5, 10 };
Console.Write("[");

for (int i = 0; i < pL.Count-1; i++)
    Console.Write("{0}, ", pL[i]);

Console.Write(pL[pL.Count-1] + "]");

但是有没有更好的方法,体积更小。

2 个答案:

答案 0 :(得分:1)

String.Join 可以采用任何可枚举(List<string> 是),因此可以使用逗号连接列表中的所有项目

var result = String.Join(", ", pL);

你也可以使用string interpolation,所以

Console.WriteLine($"[{string.Join(", ", pL)}]");

答案 1 :(得分:1)

您可以加入列表并连接前后缀

List<int> pL = new List<int> { 1, 3, 5, 10 };
var result = "[" + String.Join(", ", pL) + "]";
Console.WriteLine(result);