I need to generate a report csv with this structure
public class ReportColumn
{
public string Name { get; set; }
public List<string> Childs { get; set; } = new List<string>();
}
to this CSV structure
Header field 1; Header field 2; Header field 3
lorem ipsum; lorem ipsum; lorem ipsum;
lorem ipsum; lorem ipsum; lorem ipsum;
My difficult is to relate the correct line field with their column parent
public string DrawCsv(List<ReportColumn> reportColumns)
{
}
CodePudding user response:
It seems impossible =)
CSV is a row-oriented structure. You need to reorganize your data.
For example, create a model that corresponds to your row:
public class ReportRow
{
[Description("Name 1")]
public string Column1 { get; set; }
[Description("Name 2")]
public string Column2 { get; set; }
[Description("Name 3")]
public string Column3 { get; set; }
}
In this case, the method that makes CSV string will be:
public static string DrawCsv(List<ReportRow> rows, bool showHeader = false)
{
var result = string.Empty;
if (showHeader)
{
var header = string.Empty;
var r = rows.First();
foreach (var prop in r.GetType().GetProperties())
{
DescriptionAttribute attr = (DescriptionAttribute)prop.GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
header = attr.Description "; ";
}
result = header.TrimEnd() Environment.NewLine;
}
foreach (var row in rows)
{
var line = string.Empty;
foreach (var prop in row.GetType().GetProperties())
{
line = prop.GetValue(row) "; ";
}
result = line.TrimEnd() Environment.NewLine;
}
return result;
}
With DescriptionAttribute
you are able to avoid creating a special field for column naming.
Now we can test this:
var reportRows = new List<ReportRow>
{
new ReportRow { Column1 = "Lorem ipsum 1", Column2 = "dolor sit 1", Column3 = "amet 1" },
new ReportRow { Column1 = "Lorem ipsum 2", Column2 = "dolor sit 2", Column3 = "amet 2" },
new ReportRow { Column1 = "Lorem ipsum 3", Column2 = "dolor sit 3", Column3 = "amet 3" }
};
var str = DrawCsv(reportRows, true);
Result will be:
Name 1; Name 2; Name 3;
Lorem ipsum 1; dolor sit 1; amet 1;
Lorem ipsum 2; dolor sit 2; amet 2;
Lorem ipsum 3; dolor sit 3; amet 3;
I hope it helps you =)