Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way to Add Character at First, End and Between of each string in List of string

This is my list:

List<string> elements = new List<string> { "apple", "orange", "peach" };

I need a method with this return value:

string result = "'apple', 'orange', 'peach'";

As you see the result add "'" to the first of each string, also at the end of them, then all of them joined with ", ". So what is your suggestion to do it fast and fluent? also consider performance issues, and maybe this list have been a lot of elements, how about that?

like image 715
Saeid Avatar asked May 31 '12 05:05

Saeid


Video Answer


2 Answers

Throwing my suggestion in:

string result = string.Join(", ", elements.Select(e => "'" + e + "'"));
like image 126
Iain Avatar answered Oct 04 '22 12:10

Iain


How about

string result = string.Empty;

if (elements.Count > 0) 
    result = "'" + string.Join("', '", elements) + "'"
like image 35
Nikhil Agrawal Avatar answered Oct 04 '22 11:10

Nikhil Agrawal