我在下面的结构中有一个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)
您可以使用字符串内插来做到这一点linq,如下所示:
string.Join(", ", list.Select(t => $"['{t.Item1}', '{t.Item2}']"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3989 次 |
| 最近记录: |