CSV import into class with nested class

Spunny 366 Reputation points
2025-04-02T17:07:54.3066667+00:00

Prefer to not use installing any utilities from market place or anywhere. If possible would like to use system.IO.file object.

Hi I have a class with sub class as property like this:
public class main1

private string _name;

private string _val;

private PartyDetails _party;

List<ACModel> _acctlist;

{

public string name 

{

     get {return _name;}

     set { _name = value;}

}

public string val (get and set)

public PartyDetails Party (get and set)

public List<ACModel> acctlist (get and set)

}

//========

public class PartyDetails

{

     //list of properties here like address1, city, state, zip

}

//============

public class ACModel

{

 public int ActCode (get and set properties)

}

Now, I get CSV file like this:

 

Name Val Address1 City State Zip Actcode Actcode Actcode
Name Val Address1 City State Zip Actcode Actcode Actcode
xxx Good Xyz SFO CA 77865 111 222 333
Yyy Badd Jinni NY NY 86843 111 555 010

 

This should be converted to above class

Name and val should go into main class properties

Add1, city, state and zip should go into property Party Details which is a class

Then first row actcodes 111,222 and 333 should be created as list of objects of ACModel class into a property acctlist. For this ActCode columns can be dynamic. User can enter any number of columns.

How do I do this class generation out of csv file in c#

please suggest.

Thank you

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Anonymous
    2025-04-03T02:53:11.14+00:00

    Hi @Spunny , Welcome to Microsoft Q&A,

    You can read the CSV file using System.IO.File.ReadAllLines and parse the data by Split('\t') (if tab delimited) or Split(',') (if comma delimited) and then map it into your class structure.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    namespace xxx
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                string filePath = "output.csv"; // CSV file path
                List<main1> records = ParseCsvToClass(filePath);
    
                // Output parsed object
                foreach (var record in records)
                {
                    Console.WriteLine($"Name: {record.name}, Value: {record.val}");
                    Console.WriteLine($"Address: {record.Party.Address1}, {record.Party.City}, {record.Party.State}, {record.Party.Zip}");
                    Console.WriteLine("Account code:");
                    foreach (var acct in record.acctlist)
                    {
                        Console.WriteLine($" {acct.ActCode}");
                    }
                    Console.WriteLine("-------------------------");
                }
                Console.ReadLine();
            }
    
            public static List<main1> ParseCsvToClass(string filePath)
            {
                var lines = File.ReadAllLines(filePath);
                if (lines.Length < 2) return new List<main1>(); // Make sure there is at least a header and a row of data
    
                string[] headers = lines[0].Split(','); // Use tab delimiter, CSV replaces '\t' with ','
                List<main1> records = new List<main1>();
    
                // Dynamically find column index
                int nameIndex = Array.IndexOf(headers, "Name");
                int valIndex = Array.IndexOf(headers, "Val");
                int addressIndex = Array.IndexOf(headers, "Address1");
                int cityIndex = Array.IndexOf(headers, "City");
                int stateIndex = Array.IndexOf(headers, "State");
                int zipIndex = Array.IndexOf(headers, "Zip");
    
                // Get all Actcode column indexes
                List<int> actCodeIndexes = headers
                .Select((col, index) => (col, index))
                .Where(x => x.col.StartsWith("Actcode"))
                .Select(x => x.index)
                .ToList();
    
                for (int i = 1; i < lines.Length; i++) // Skip headers starting from 1
                {
                    var cols = lines[i].Split(','); // CSV replaces '\t' with ','
    
                    var record = new main1
                    {
                        name = nameIndex >= 0 ? cols[nameIndex] : "",
                        val = valIndex >= 0 ? cols[valIndex] : "",
                        Party = new PartyDetails
                        {
                            Address1 = addressIndex >= 0 ? cols[addressIndex] : "",
                            City = cityIndex >= 0 ? cols[cityIndex] : "",
                            State = stateIndex >= 0 ? cols[stateIndex] : "",
                            Zip = zipIndex >= 0 ? cols[zipIndex] : ""
                        },
                        acctlist = actCodeIndexes
                     .Where(idx => idx < cols.Length)
                     .Select(idx => new ACModel { ActCode = int.TryParse(cols[idx], out int code) ? code : 0 })
                     .ToList()
                    }; records.Add(record);
                }
    
                return records;
            }
        }
    
        // Main class
        public class main1
        {
            public string name { get; set; }
            public string val { get; set; }
            public PartyDetails Party { get; set; }
            public List<ACModel> acctlist { get; set; }
        }
    
        //Address information class
        public class PartyDetails
        {
            public string Address1 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string Zip { get; set; }
        }
    
        // Account code class
        public class ACModel
        {
            public int ActCode { get; set; }
        }
    }
    

    output:

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.