Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to import a CSV file into a class which begins with a number of strings, and ends with some control fields.

If I use http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp and change the display to populate a class of strings, is there a way to dynamically do this?

Could I index each field like classInstance[i]. Or would I have to read each field individually and add in position, and validate the end of file by adding blank entries to the remaining fields.

C#
read stringContents;
if (stringContents) 
{
classInstance.position1 = stringContents;}
else
{
classInstance.position1 = "";
}
read stringContents;
if (stringContents)
{
classInstance.position2 = stringContents;}
else
{
classInstance.position2 = "";
}


stringContents is a bool method = false if end of file etc.

The Class current has 34 fields with the first 20 for the string imports and the remaining 14 to control the application.
Posted
Comments
BillWoodruff 10-Nov-14 10:05am    
Does the CSV file contain data for only one instance of a Class, or multiple instances of a Class ? What is the content of the 'control fields:' will those fields need some kind of conversion from string when they are read ?
AndrewDay 10-Nov-14 10:10am    
There are 200+ records typically.
I want to combine upto 20x string elements by position, with 14 application control fields. The 20x fields of data which have an unknown order, are displayed very simply and thats all, whilst the 14 other fields make the application usefull and capture the users comments, status changes etc, and make a simple progress chaser. The arrangement of the alien data wont change over time.
BillWoodruff 10-Nov-14 10:24am    
I appreciate your clarification, but I have to still ask the same two questions I asked before. What does each of those 200 records become ? How many classes with 34 fields do you create ?
AndrewDay 10-Nov-14 10:40am    
Ok, I have basic data which is typically
AcctNumber,Name,Status1,Status2,Period1,Period2
ABC123,Abc Ltd,Good,Good,March,April
SOP100,Sophie Ltd,Good,Good,March,April
Execpt that there are 200+ records ordinarily and upto 20x fields which can comprise of a number of things as a "Printout" type of output. I want to add these to a 34x field class, with the last 14x fields being dates, notes and user defined statues. The first 20x fields do not change unless updated by the software that gave the "Printout", and I can update them once I know how to convert them into the class instance. The last 14x fields make the application useful, and are unconnected to the 20x fields which are for display only.
BillWoodruff 10-Nov-14 11:43am    
Well, I surrender; I can't force you to answer my questions :) By the way, imho the article you link is not very high quality, and has no downloadable source; I believe this CP article has much better code and content, and it includes downloadable source: "A Fast CSV Reader," bySebastien Lorion:

http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

if you use the above code, also see:

http://stackoverflow.com/a/21605485/133321

C#
var classInstance = File.ReadLines(csvfilePath)
               .Select(line => line.Split(','))
               .Select(fields=> new MyClass { Field0 = fields[0], Field1 = fields[1] })
               .ToList();

then you can access your instances from position like classInstance[0], classInstance[1]

UPDATE:
without LINQ
C#
class Program
{
    static void Main(string[] args)
    {
        List<MyClass> classInstance = new List<MyClass>();
        var lines = File.ReadLines("CsvFile.csv");
        foreach (string line in lines)
        {
            var fields = line.Split(',');
            classInstance.Add(new MyClass() { Field0 = fields[0], Field1 = fields[1] });
        }
    }
}
public class MyClass
{
    public string Field0 { get; set; }
    public string Field1 { get; set; }
    // define all other fields
}
 
Share this answer
 
v2
Comments
AndrewDay 10-Nov-14 10:42am    
I take it that this is a Linq query, I have no experience here.
It looks very elegant, and TOO easy!
Hope I can get this working like this, and mark you off as the solution.

Thanks in the meantime
DamithSL 10-Nov-14 10:47am    
you don't need to do it with Linq, wait I'll update the solution, give me some time :)
AndrewDay 10-Nov-14 12:10pm    
Thats excellent, can I just ask. What is the default behaviour if the line in lines dosent cover all 20x fields. If its a null or empty string that would do it. Let me know please.
I have to collect my daughter and will start again tomorrow :)
DamithSL 10-Nov-14 12:18pm    
why don't you run and test?
AndrewDay 12-Nov-14 11:53am    
I did, the code is great. However I don't know in advance how many fields there will be. From your code would you recommend setting "lines" to 20x blank fields and overwrite with data fields found.
Is there a way to do that, or would I empty/copy var lines into an array?
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace APAR_csvTryout
{
    class Program
    {
        static void Main(string[] args)
        {

            List<myclass> classInstance = new List<myclass>();
            var lines = File.ReadLines(@"..\..\AcctSummaryInCSV.csv");
            foreach (string line in lines)
            {
                var fields = line.Split(',');
                //var count = postions.Count;
                var count = fields.Count();

                string[] postions = new string[20];

                for (int i = 0; i < count; i++)
                {
                    postions[i] = fields[i];
                }
                
                for (int i = count; i < 20; i++)
                {
                    postions[i] = "";
                }


                    classInstance.Add(new MyClass()
                    {
                        Field0 = postions[0],
                        Field1 = postions[1],
                        Field2 = postions[2],
                        Field3 = postions[3],
                        Field4 = postions[4],
                        Field5 = postions[5],
                        Field6 = postions[6],
                        Field7 = postions[7],
                        Field8 = postions[8],
                        Field9 = postions[9],
                        Field10 = postions[10],
                        Field11 = postions[11],
                        Field12 = postions[12],
                        Field13 = postions[13],
                        Field14 = postions[14],
                        Field15 = postions[15],
                        Field16 = postions[16],
                        Field17 = postions[17],
                        Field18 = postions[18],
                        Field19 = postions[19]                        
                    });
            }
        }
    }
    public class MyClass
    {
        public string Field0 { get; set; }
        public string Field1 { get; set; }
        public string Field2 { get; set; }
        public string Field3 { get; set; }
        public string Field4 { get; set; }
        public string Field5 { get; set; }
        public string Field6 { get; set; }
        public string Field7 { get; set; }
        public string Field8 { get; set; }
        public string Field9 { get; set; }
        public string Field10 { get; set; }
        public string Field11 { get; set; }
        public string Field12 { get; set; }
        public string Field13 { get; set; }
        public string Field14 { get; set; }
        public string Field15 { get; set; }
        public string Field16 { get; set; }
        public string Field17 { get; set; }
        public string Field18 { get; set; }
        public string Field19 { get; set; }
    }
}</myclass></myclass>
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900