WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

Using linq to build a comma delimited string

I need to generate a string that has a comma delimited list, but no comma after the last element.

var x = new List<string>() { "a", "b", "c" };

should yield:

a,b,c

Yes, a very simple thing to do using "normal" techniques, but I hope with linq there is a more elegant way.

var cols =context.Database.SqlQuery<String>("select Column_Name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = {0};", prefix + table);

Upvotes: 0

Views: 367

Answers (3)

Abbas
Abbas

Reputation: 14432

Although I strongly recommend you use the answer of Siva Charan, just for information here's an implementation in LinQ using Enumerable.Aggregate Method (IEnumerable, Func):

var result = x.Aggregate((c, n) => c + "," + n);

Upvotes: 0

Jignesh Thakker
Jignesh Thakker

Reputation: 3698

String class provide Join method to join string array with delimiter.

Code:

var x = new List<string>() { "a", "b", "c" };
String.Join(",",x.ToArray());

documentation: http://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx

Upvotes: 0

Siva Charan
Siva Charan

Reputation: 18064

No need Linq, just use String.Join

String.Join(",", new List<string>() { "a", "b", "c" });

Upvotes: 2

Related Questions