7

I'd like to make a comma seperated value string with Linq's Aggregate function. Anyone know how to do this?

Given an array of strings like this:

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

How do I get a single string like this author 1, author 2, author 3? I'm thinking something like authors.Aggregate(author => author + ",") might be able to do this but not sure.

Ideas?

Ani
  • 111,048
  • 26
  • 262
  • 307
Paul Fryer
  • 9,268
  • 14
  • 61
  • 93
  • Possible duplicate of [LINQ Aggregate algorithm explained](http://stackoverflow.com/questions/7105505/linq-aggregate-algorithm-explained) – Jamiec Oct 05 '15 at 14:49

2 Answers2

12

If you're only looking to comma-separate them, just use string.Join:

string.Join(", ", authors);

This will work with any IEnumerable<string> (at least in .NET 4.0), but has worked with arrays of strings since 1.0.

Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
7

As Bennor McCarthy says, you'd be much better off using string.Join for this purpose. If you really do want to use Enumerable.Aggregate though, this should do:

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;
}
Ani
  • 111,048
  • 26
  • 262
  • 307