Search code examples
vb.netstringbuilderrecords

How to output data from Structure to CSV using StringBuilder


I have data in the following structure:

Structure student
    Dim stdntpass As String
    Dim fname As String
    Dim sname As String
    Dim age As Byte
    Dim year As Integer
    Dim stdntuser As String
End Structure

I need to take the data in that structure and output it to CSV. I was planning on using a StringBuilder object to do it, but I can't figure out how to give the structure to the StringBuilder.


Solution

  • Here is a function that uses reflection to determine what fields exist in the student structure:

    Public Function StudentsToCSV(students As IEnumerable(Of student)) As String
        Const separator As Char = ";"c
        Dim sb As New StringBuilder
    
        'Get the data elements
        Dim studentFields = GetType(student).GetFields()
    
        'Output headline (may be removed)
        For Each field In studentFields
            sb.Append(field.Name)
            sb.Append(separator)
        Next
        sb.AppendLine("")
    
        'Write a line for each student
        For Each s In students
            'Write the value of each field
            For Each field In studentFields
                Dim value As String = Convert.ToString(field.GetValue(s))
                sb.Append(value)
                '... followed by the separator
                sb.Append(separator)
            Next
            sb.AppendLine("")
        Next
        Return sb.ToString()
    End Function
    

    You can pass any set of students to this function - may it be an array, a List(Of student) or whatever.