直接上代码:
//保存二维数组数据到CSV文件
static void SaveToCsv(List<List<double>> data, string filePath)
{
try
{
// 使用 StreamWriter 创建一个新的 CSV 文件
using (StreamWriter sw = new StreamWriter(filePath))
{
// 遍历二维列表并将其写入 CSV 文件
foreach (List<double> row in data)
{
// 将每一行的元素连接成字符串,使用逗号分隔
string rowString = string.Join(",", row);
// 写入当前行
sw.WriteLine(rowString);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
//读取CSV文件的一维数组到List
static List<double> ReadCSV(string filePath)
{
List<double> data = new List<double>();
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
if (!string.IsNullOrEmpty(line))
{
string[] values = line.Split(',');
foreach (string value in values)
{
double number = Convert.ToDouble(value);
data.Add(number);
}
}
}
return data;
}