C# 如何高效地将大型2D数组写入CSV文件
编辑:使用提供的解决方案,我能够通过以下方式使其工作(不是最有效的,但它可以工作):C# 如何高效地将大型2D数组写入CSV文件,c#,.net,C#,.net,编辑:使用提供的解决方案,我能够通过以下方式使其工作(不是最有效的,但它可以工作): public static void WriteArray(object[,] dataArray, string filePath, bool deleteFileIfExists = true) { if (deleteFileIfExists && File.Exists(filePath)) { File.Delet
public static void WriteArray(object[,] dataArray, string filePath, bool deleteFileIfExists = true)
{
if (deleteFileIfExists && File.Exists(filePath))
{
File.Delete(filePath);
}
byte columnCount = (byte) dataArray.GetLength(1);
int rowCount = dataArray.GetLength(0);
for(int row = ReadExcel.ExcelIndex; row <= rowCount; row++)
{
List<string> stringList = new List<string>();
for(byte column = ReadExcel.ExcelIndex; column <= columnCount; column++)
{
stringList.Add(dataArray[row, column].ToString());
}
string rowAsString = StringifyRow(stringList.ToArray());
WriteLine(filePath, rowAsString);
}
}
public static string StringifyRow(string[] row)
{
return string.Join(",", row);
}
public static void WriteLine(string filePath, string rowAsString)
{
using (StreamWriter writer = new StreamWriter(filePath, append: true))
{
writer.WriteLine(rowAsString);
writer.Flush();
}
}
public static void WriteArray(对象[,]数据数组,字符串文件路径,bool deleteFileIfExists=true)
{
if(deleteFileIfExists&&File.Exists(filePath))
{
File.Delete(文件路径);
}
byte columnCount=(字节)dataArray.GetLength(1);
int rowCount=dataArray.GetLength(0);
对于(int row=ReadExcel.ExcelIndex;row,使用下面这样的代码,我从来没有遇到过任何内存问题,即使使用了大量数据
class Program
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter("Filename");
List<Record> data = new List<Record>();
foreach (Record record in data)
{
string line = string.Join(",", record.field1, record.field2, record.field3, record.field4, record.field5);
writer.WriteLine(line);
}
writer.Flush();
writer.Close();
}
}
public class Record
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
public string field5 { get; set; }
}
类程序
{
静态void Main(字符串[]参数)
{
StreamWriter writer=新的StreamWriter(“文件名”);
列表数据=新列表();
foreach(数据中的记录)
{
字符串行=string.Join(“,”,record.field1,record.field2,record.field3,record.field4,record.field5);
writer.WriteLine(行);
}
writer.Flush();
writer.Close();
}
}
公开课记录
{
公共字符串字段1{get;set;}
公共字符串字段2{get;set;}
公共字符串字段3{get;set;}
公共字符串字段4{get;set;}
公共字符串字段5{get;set;}
}
非常感谢。我能够使用您提供的示例进行一些修改,并且效果良好。我将在问题中发布工作代码。
class Program
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter("Filename");
List<Record> data = new List<Record>();
foreach (Record record in data)
{
string line = string.Join(",", record.field1, record.field2, record.field3, record.field4, record.field5);
writer.WriteLine(line);
}
writer.Flush();
writer.Close();
}
}
public class Record
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
public string field5 { get; set; }
}