Linq Aggregate Function, How to create a CSV string

I would like to make a comma delimited string with the Linq Aggregate function. Does anyone know how to do this?

For an array of such lines:

var authors = new string[] {"author 1", "author 2", "author 3"}; 

How to get one line, such as author 1, author 2, author 3 ? I think something like authors.Aggregate(author => author + ",") can do this, but not sure.

Ideas?

+6
string linq csv aggregate
source share
2 answers

If you are only viewing a comma, separate them, just use string.Join:

 string.Join(", ", authors); 

This will work with any IEnumerable <string> (at least in .NET 4.0), but works with string arrays from 1.0.

+11
source share

As Benner McCarthy says, for this purpose you will be much better off using string.Join . If you really want to use Enumerable.Aggregate , this should do the following:

 string csvString = authors.Aggregate((csvSoFar, author) => csvSoFar + ", " + author); 

This is roughly equivalent to:

 string csvString = authors.First(); foreach (string author in authors.Skip(1)) { csvString += ", " + author; } 
+6
source share

All Articles