RaceBase
RaceBase

Reputation: 18848

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?

Upvotes: 15

Views: 30463

Answers (5)

Josh P
Josh P

Reputation: 1355

NOTE: if you're starting with IEnumerable or similar you have to call .ToArray() at the end of the LINQ statement like this:

input parameter: IEnumerable<string> feederIdList    

var feederListString = String.Join(",", feederIdList.Select(feeder => "\"" + feeder + "\"").ToArray());

In my case I needed each string to have double quotes around it for passing into an Oracle stored procedure later.

Upvotes: 0

Espen
Espen

Reputation: 2576

You could also use the Aggregate method: Example:

List<string> fruit = new List<string> {"Apple", "Orange", "Pear", "Tomato", "Banana"};
var fruitSentence = fruit.Aggregate((current, next) => $"{current},{next}");

Upvotes: 0

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59111

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.

Upvotes: 31

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

You can use aggregate linq

Array.Skip(1).Aggregate(Array[0],(a,b) => string.Format("{0},'{1}'",a,b));

Upvotes: 3

Backs
Backs

Reputation: 24903

String[] data = new String[]{"test","abc","123"};
var result = string.Join(",", data.Select(o => string.Concat("'",o,"'"));

Upvotes: 1

Related Questions