Search code examples
c#csvcsvhelper

Csvhelper - read / get a single column of all rows?


Hi I'm using csvHelper to read in a csv files with a variable number of columns. The first row always contains a header row. The number of columns is unknown at first, sometimes there are three columns and sometimes there are 30+. The number of rows can be large. I can read in the csv file, but how do I address each column of data. I need to do some basic stats on the data (e.g. min, max, stddev), then write them out in a non csv format. Here is my code so far...

try{
    using (var fileReader = File.OpenText(inFile))
    using (var csvResult  = new CsvHelper.CsvReader(fileReader))
    {
        // read the header line   
        csvResult.Read();

        // read the whole file
        dynamic recs = csvResult.GetRecords<dynamic>().ToList();

        /* now how do I get a whole column ???
         * recs.getColumn ???
         * recs.getColumn['hadername'] ???
         */

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }

Thanks


Solution

  • I don't think the library is capable of doing so directly. You have to read your column from individual fields and add them to a List, but the process is usually fast because readers do job fast. For example if your desired column is of type string, the code would be like so:

    List<string> myStringColumn= new List<string>();
    using (var fileReader = File.OpenText(inFile))
        using (var csvResult  = new CsvHelper.CsvReader(fileReader))
        {
            while (csvResult.Read())
           {
             string stringField=csvResult.GetField<string>("Header Name");
             myStringColumn.Add(stringField);    
           }
        }