I have a double[][]
that I want to convert to a CSV string format (i.e. each row in a line, and row elements separated by commas). I wrote it like this:
public static string ToCSV(double[][] array)
{
return String.Join(Environment.NewLine,
Array.ConvertAll(array,
row => String.Join(",",
Array.ConvertAll(row, x => x.ToString())));
}
Is there a more elegant way to write this using LINQ?
(I know, one could use temporary variables to make this look better, but this code format better conveys what I am looking for.)
You could also use Aggregate
You can do it with LINQ, but I'm not sure if you like this one better than yours. I'm afraid you don't. :)
Cheers, Matthias
This is compatible with any nested sequences of
double
. It also defers theToString
implementation to the caller, allowing formatting while avoiding messyIFormatProvider
overloads:You can, but I wouldn't personally do all the lines at once - I'd use an iterator block:
This returns each line (the caller can then
WriteLine
etc efficiently, without buffering everything). It is also now callable from any source ofdouble[]
rows (including but not limited to a jagged array).Also - with a local variable you could use
StringBuilder
to make each line slightly cheaper.To return the entire string at once, I'd optimize it to use a single
StringBuilder
for all the string work; a bit more long-winded, but much more efficient (far fewer intermediate strings):