Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array of Strings to Comma Separated String with additional concatenation

Is there any way to convert a list of strings to a comma-separated string?

String[] data = new String[] { "test", "abc", "123" }

Convert into:

'test', 'abc', '123'

Possible solutions:

  1. Surround every string with '' and then use String.join on the list.
  2. Foreach each string in the list and do the concatenation of '' and ',' and in the end remove last ','

Is there any simple Linq (one line expression) to do both?

like image 838
RaceBase Avatar asked Nov 02 '15 05:11

RaceBase


2 Answers

Is there any simple Linq (one line expression) to do both.

string.Join(",", data.Select(item => "'" + item + "'"))

Basics of Linq: Transforms are Select statements. Filters are Where statements.

That said, there are a lot of string manipulation tools available that aren't Linq, and they're more likely to be optimized for strings, so I'd always look to them before looking to Linq.

like image 177
Merlyn Morgan-Graham Avatar answered Oct 05 '22 07:10

Merlyn Morgan-Graham


You can use aggregate linq

Array.Skip(1).Aggregate(Array[0],(a,b) => string.Format("{0},'{1}'",a,b));
like image 34
M.kazem Akhgary Avatar answered Oct 05 '22 05:10

M.kazem Akhgary