Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

.net

linq

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 IEnumberable.Aggregate inside a foreach loop?

results.SelectMany(x => x).Aggregate((c, n) => c + ", " + n)
like image 468
evanmcdonnal Avatar asked Aug 09 '13 18:08

evanmcdonnal


2 Answers

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());
like image 143
Sergey Berezovskiy Avatar answered Nov 08 '22 11:11

Sergey Berezovskiy


results.Select(sa => sa.Aggregate((a, b) => a + ", " + b))
       .Aggregate((c, d) => c + Enviroment.NewLine + d);
like image 33
It'sNotALie. Avatar answered Nov 08 '22 12:11

It'sNotALie.