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

时间:2016-01-22 04:15:18

标签: c# string

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

Tuple<string, string>
像这样:

enter image description here

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

['A', '1'],['B', '2'], ['C', '3']...

现在我正在使用以下代码:

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

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

5 个答案:

答案 0 :(得分:7)

您可以使用Linq,string.Joinstring.Format使其更紧凑:

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

答案 1 :(得分:4)

您可以使用linqstring interpolation执行此操作:

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

答案 2 :(得分:2)

There are some benchmarking(注意:每个字都包含一个链接,但我认为最好的参考之一是this。)如何加入string

引用引用:

  

Rico Mariani,.NET性能大师,就此而言an article   学科。它的并不像人们怀疑的那么简单

您可以查看string.Concatstring.Builder,特别是它们通常比+运营商更快。

我在这里使用string.Concat

string str = string.Concat(new string[] { "[ '", list[i].Item1, "', '", list[i].Item2, "']," });

答案 3 :(得分:1)

您也可以使用LINQ:

var input = new List<Tuple<string, string>> { Tuple.Create("A", "1"), Tuple.Create("B", "2") };
var result = String.Join(",", input.Select(elem => "[ '" + elem.Item1 + "', '" + elem.Item2 + "']"));
Console.WriteLine(result);

答案 4 :(得分:1)

这也可能适合你

var input = new List<Tuple<string, string>> 
                { 
                    Tuple.Create("A", "1"), 
                    Tuple.Create("B", "2"), 
                    Tuple.Create("C", "3") 
                };
string tpljoined = string.Join(", ", 
                        input.Select(x => "['" + x.Item1 + "','" + x.Item2 + "']"));
相关问题