How can I build a string from a collection with Linq?

linq, string, vb.net

Solution

Have you tried a simple join?..

if field.Values is already an array of strings then this should work fine.. otherwise you could use LINQ `.ToArray()` to convert the collection to an array.

string joined = string.Join(Environment.NewLine, field.Values);

VB

Dim joined As String = String.Join(Environment.NewLine, field.Values)

Just figured I would add, if you really, really just wanted to do this with LINQ a Aggregrate would work, although I wouldn't really recommend this for your needs.

field.Values.Aggregate(string.Empty, (s1, s2) => s1 += Environment.NewLine + s2);

Problem

I'm building flat file content from collections of strings. Example collection: A, B, C, D, E, etc. I want to be able to output these values to a string with line feeds in one swoop with Linq if possible. Sample Output: A B C D E etc. Here's the VB.NET code that does the job currently: ``` For Each fieldValue As String In field.Values fileContent.Append(fieldValue + Environment.NewLine) Next ``` I've tried a bunch of ways to get Linq to do the job, but haven't been able to find the right combination. Thoughts?

Original source