Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / file

Quick, Simple and Elegant way to convert C# data model to CSV

5.00/5 (2 votes)
18 Aug 2019CPOL1 min read 10.8K   114  
CSV file generator using simplistic approach

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:

C++
[
  {
    "MemberName": "David",
    "MemberNumber": "1"
  },
  {
    "MemberName": "Joseph",
    "MemberNumber": "2"
  }
]

Deserialize the data:

C++
var listMemberData=JsonConvert.DeserializeObject<IEnumerable<MemberData>>
                   (File.ReadAllText("MemberData.json"));

Define ColumnDataMapper - Maps each of the cells:

C++
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):

C++
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:

C++
public static StringBuilder GenerateFileContent(IEnumerable<MemberData> listMemberData)
        {
            StringBuilder sbOutput = new StringBuilder();

            //Generate Header
            sbOutput.AppendLine(string.Join
             (DataSeparator, DataMappers.MemberDataMappers.Select(p => p.HeaderName)));

            //Generate rows
            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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)