我可以更优雅重写这个使用LINQ? [英] Can I rewrite this more elegantly using LINQ?
问题描述
我有一个双击[] []
,我想转换为CSV字符串格式(即每行中的一行,并以逗号分隔行元素)。我写的是这样的:
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())));
}
有没有更优雅的方式来写这个使用LINQ?
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.)
推荐答案
这是兼容双
,也推迟了的ToString
的实施给调用者,允许同时避免凌乱的IFormatProvider
重载格式化:
This is compatible with any nested sequences of double
. It also defers the ToString
implementation to the caller, allowing formatting while avoiding messy IFormatProvider
overloads:
public static string Join(this IEnumerable<string> source, string separator)
{
return String.Join(separator, source.ToArray());
}
public static string ToCsv<TRow>(this IEnumerable<TRow> rows, Func<double, string> valueToString)
where TRow : IEnumerable<double>
{
return rows
.Select(row => row.Select(valueToString).Join(", "))
.Join(Environment.NewLine);
}
这篇关于我可以更优雅重写这个使用LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!