Search code examples
c#.netstringlinq

Flatten List<string[]> into single string with one line for each element


I have an instance of type List<string[]> I would to convert this to a string with a each string[] on a newline. I'm using the following LINQ query to flatten out the list however I'm not sure how I can add a new line between each string[] without expanding my query into something far more ugly. Is there a way to do it without gutting my query and using String.Join or IEnumerable.Aggregate inside a foreach loop?

results.SelectMany(x => x).Aggregate((c, n) => c + ", " + n)

Solution

  • String.Join(Environment.NewLine, results.Select(a => String.Join(", ", a)));
    

    Complete sample:

    var results = new List<string[]> {
        new[]{"this", "should", "be", "on"},
        new[]{"other", "line"}
    };
    
    var result = String.Join(Environment.NewLine, 
                             results.Select(a => String.Join(", ", a)));
    

    Result:

    this, should, be, on
    other, line
    

    UPDATE Here is aggregation done right - it uses StringBuilder to build single string in memory

    results.Aggregate(new StringBuilder(),
                      (sb, a) => sb.AppendLine(String.Join(",", a)),
                      sb => sb.ToString());