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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

O Cool, I guess Aggregate is not really what I need. Looks like Join is the right thing. I'll give try this... thanks.
Good call - I forgot about that method!
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;
}

1 Comment

Thanks, Ya looks like Join is much is a much simpler approach for this task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.