将元组列表转换为字符串的更好方法

Use*_*384 2 c# string

我在下面的结构中有一个List:

Tuple<string, string>
Run Code Online (Sandbox Code Playgroud)

像这样:

在此输入图像描述

我想加入列表,形成如下字符串:

['A', '1'],['B', '2'], ['C', '3']...
Run Code Online (Sandbox Code Playgroud)

我现在使用下面的代码来做:

string result = "";
for (int i = 0; i < list.Count; i++)
{
      result += "[ '" + list[i].Item1 + "', '" + list[i].Item2 + "'],";
}
Run Code Online (Sandbox Code Playgroud)

代码工作正常,但想问是否有更好的方法可以做到这一点?

D S*_*ley 12

您可以使用Linq使其更紧凑,string.Join并且string.Format:

result = string.Join(",", list.Select(t => string.Format("[ '{0}', '{1}']", t.Item1, t.Item2)));
Run Code Online (Sandbox Code Playgroud)

  • 我的更好,因为 'x' &gt; 't' :) (2认同)

Ari*_*ian 6

您可以使用字符串内插来做到这一点linq,如下所示:

string.Join(", ", list.Select(t => $"['{t.Item1}', '{t.Item2}']"));
Run Code Online (Sandbox Code Playgroud)