Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better ways to convert tuple list to string

Tags:

string

c#

I have a List in below structure:

Tuple<string, string>

like this:

enter image description here

And I would like to join the list to form a string like below:

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

And I am now using below code to do:

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

The code works OK, but would like to ask if there're any better ways to do that?

like image 929
User2012384 Avatar asked Jan 22 '16 04:01

User2012384


1 Answers

You can make it more compact by using Linq, string.Join and string.Format:

result = string.Join(",", list.Select(t => string.Format("[ '{0}', '{1}']", t.Item1, t.Item2)));
like image 83
D Stanley Avatar answered Oct 18 '22 12:10

D Stanley