解决方案是获取属性名称和属性数据字段值:
public static void ExportList<T>(string savefileNamePath, List<T> data, string delimiter, string textQualifier)
{
foreach (var prop in data.GetType().GetProperties())
{
prop.Name // use to get feild name data
}
foreach (var row in data)
{
foreach (var prop in row.GetType().GetProperties())
{
//use to get field Data of All rows
var value = prop.GetValue(row, null).ToString();
}
}
}
我需要写一些遍历未知List类数据的内容并将其导出到带分隔符的文本文件中。我将只能在运行时访问类类型,并且每次运行都会更改。字段名称不能进行硬编码,因为它们在每次运行时都会更改。我已经找到了如何获取属性/字段名称,但是我一生都无法确定如何解析每个记录上的各个字段值,因此无法以正确的格式输出它们。
在此示例中,它将T类字段名称输出到输出文本文件第一行上的文件。现在,我需要弄清楚如何在我通过的测试List类中导出实际的20条记录的各个字段数据值。谢谢。希望有人可以指出正确的方向。非常感谢...
输出第1行:“容量”,“计数”,“项目”
质量检查测试调用代码:
public class TestDataClassDto
{
public string FieldData1 { get; set; }
public DateTime FieldData2 { get; set; }
public long FieldData3 { get; set; }
}
public void Check_ExportList()
{
/* create test data to export to a file */
List<TestDataClassDto> dataList = new List<TestDataClassDto>();
for (int i = 0; i < 20; i++)
{
var data = new TestDataClassDto()
{
FieldData1 = $@"Test Data {i}",
FieldData2 = DateTime.Now,
FieldData3 = i
};
dataList.Add(data);
}
//create unique name fortest run
string OutputFile = $@"d:\Temp\Exportlist_{DateTime.Now.Hour}_{DateTime.Now.Minute}_{DateTime.Now.Second}_{DateTime.Now.Millisecond}.txt";
/* export test data delimiter: comma, text qualifier: " */
DelimitCheckLib.DelimitCheckLib.ExportList<TestDataClassDto>(OutputFile, dataList, ",", ((char)34).ToString());
}
将列表导出到定界文件的方法:
public static void ExportList<T>(string savefileNamePath, List<T> data, string delimiter, string textQualifier)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter($@"{savefileNamePath}", true))
{
Console.WriteLine($"Writing Data File: {savefileNamePath}");
StringBuilder line = new StringBuilder();
int fieldLocation = 0;
/* Process Field Names - always the first line of the file */
foreach (var prop in data.GetType().GetProperties())
{
/* field names first line */
if (fieldLocation == 0)
{
line.Append($@"{textQualifier}{prop.Name}{textQualifier}");
}
else
{
line.Append($@"{delimiter}{textQualifier}{prop.Name}{textQualifier}");
}
fieldLocation++;
}
file.WriteLine(line);
/* Process List Row Data Actual Field Values - below */
}
}