Introduction
Converts a C# data model to CSV formatted file. I know there are tools which do this, but I had a situation where I can't use third party libraries or tools and I had to write code for a legacy application.
Could be a good starting point or use this as template.
All it does is pass on the data to the model and it converts it to CSV data or file.
Background
There are multiple ways to achieve this. One of them is Reflection where we use reflection to get the types of the properties and then get the data, loop through all properties and generate the data.
In this article, I would specify a simple and elegant way to achieve the same. The approach really depends on the situation and problem you have.
Using the Code
Let's start with some test data as input:
[
{
"MemberName": "David",
"MemberNumber": "1"
},
{
"MemberName": "Joseph",
"MemberNumber": "2"
}
]
Deserialize the data:
var listMemberData=JsonConvert.DeserializeObject<IEnumerable<MemberData>>
(File.ReadAllText("MemberData.json"));
Define ColumnDataMapper
- Maps each of the cells:
public class ColumnDataMapper
{
public string HeaderName { get; set; }
public Func<MemberData, string> Extractor { get; set; }
}
Now define the initial structure of our Member Data (like a table having row and column):
public static readonly IEnumerable<ColumnDataMapper> MemberDataMappers = new[]
{
new ColumnDataMapper
{
HeaderName = "Member Number",
Extractor = obj => obj.MemberNumber.ToString()
},
new ColumnDataMapper
{
HeaderName = "Member Name",
Extractor = obj => obj.MemberName
}
};
Generate all data:
public static StringBuilder GenerateFileContent(IEnumerable<MemberData> listMemberData)
{
StringBuilder sbOutput = new StringBuilder();
sbOutput.AppendLine(string.Join
(DataSeparator, DataMappers.MemberDataMappers.Select(p => p.HeaderName)));
foreach (var memberData in listMemberData)
{
sbOutput.AppendLine(string.Join(DataSeparator,
DataMappers.MemberDataMappers.Select(p=>p.Extractor(memberData))));
}
return sbOutput;
}
Points of Interest
For simple structure, we could go with this method but for complex objects, I'd prefer Reflection or open source tool like FileHelpers
Library.
History
- 19th August, 2019: Initial article