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)
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());
results.Select(sa => sa.Aggregate((a, b) => a + ", " + b))
.Aggregate((c, d) => c + Enviroment.NewLine + d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With