Search code examples
c#dynamiccsvhelper

How to iterate through a column in a csv file using CSVhelper library? using: dynamic object


CSV file

CSV file in notepad editor

using CsvHelper;

public class csvread
{
   public dynamic APSSValue ;
   public async Task GetMode()
   {
      try 
      {
         FileOpenPicker openpicker = new FileOpenPicker();
         openpicker.FileTypeFilter.Add(".csv");   
         IRandomAccessStreamWithContentType stream = await file.OpenReadAsync();
         StreamReader reader = new StreamReader(stream.AsStream());
         string UserCultureInfo = Thread.CurrentThread.CurrentCulture.Name;
         CsvReader csv = new CsvReader(reader, culture: CultureInfo.CreateSpecificCulture(UserCultureInfo));
         csv.Configuration.HasHeaderRecord = false;
         csv.Configuration.Delimiter = ";";
         while (csv.Read())
         {
            APSSValue = Enumerable.ToList(csv.GetRecord<dynamic>());
         }
      }
   }
}

I tried this way shown above but with this I only get the number of columns. I also tried

csv.Read();
APSSValue = Enumerable.ToList(csv.GetRecords<dynamic>());

but this gives me the entire data of csv file.

Questions:

  • I want to look for the value under the column (I_APSS_Modus) Please see the images shared above, It can be 0 or 1 so how can I look for that value if it is 0 or 1 ?

NOTE:

  • I don't want the values of entire column because all the values in the column would be either 0 or 1. So i just want one value from any row under that column.

  • CSV file is not same every time, so the column number for (I_APSS_Modus) will vary if the CSV file is different


Solution

  • Try following code which put data into a DataTable so you can easily filter with linq. Below will work with posted csv

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Globalization;
    using System.Data;
    
    namespace ConsoleApplication8
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.txt";
            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Timestamp", typeof(DateTime));
                dt.Columns.Add("B_Kurze_Seite", typeof(Boolean));
                dt.Columns.Add("I_Partikeleinfall Reinluft", typeof(int));
                dt.Columns.Add("I_Partikeleinfall Rohluft", typeof(int));
                dt.Columns.Add("I_APSS_Modus", typeof(int));
    
                StreamReader reader = new StreamReader(FILENAME);
                string line = "";
                int row = 0;
                string format = "yyyy MM dd HH:mm:ss:fff";
                while ((line = reader.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.Length > 0 && !line.StartsWith("sep"))
                    {
                        if (++row > 1)
                        {
                            string[] splitRow = line.Split(new char[] { ';' });
                            dt.Rows.Add(new object[] {
                            DateTime.ParseExact(splitRow[0],format,CultureInfo.InvariantCulture),
                            (splitRow[1] == "FALSE")? false : true,
                            int.Parse(splitRow[2]),
                            int.Parse(splitRow[3]),
                            int.Parse(splitRow[4])
                        });
                        }
    
                    }
                }
                List<int> data = dt.AsEnumerable().Select(x => x.Field<int>("I_APSS_Modus")).ToList();
            }
        }
    
    }
    

    Here is code that will work with generic columns

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Globalization;
    using System.Data;
    
    namespace ConsoleApplication8
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.txt";
            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
    
    
                StreamReader reader = new StreamReader(FILENAME);
                string line = "";
                int row = 0;
                string format = "yyyy MM dd HH:mm:ss:fff";
                string[] columnNames = null;
                while ((line = reader.ReadLine()) != null)
                {
                    line = line.Trim();
                    if ((line.Length > 0) && !line.StartsWith("sep"))
                    {
                        string[] splitRow = line.Split(new char[] { ';' });
                        if (++row == 1)
                        {
                            columnNames = splitRow;
                            foreach (string col in splitRow)
                            {
                                switch(col)
                                {
                                    case "Timestamp":
                                        dt.Columns.Add(col, typeof(DateTime));
                                        break;
    
                                    case "I_APSS_Modus":
                                        dt.Columns.Add(col, typeof(int));
                                        break;
    
                                    default:
                                        dt.Columns.Add(col, typeof(string));
                                        break;
                                }
                            }
                        }
                        else
                        {
                            DataRow newRow = dt.Rows.Add();
                            for (int i = 0; i < columnNames.Length; i++)
                            {
                                switch (columnNames[i])
                                {
                                    case "Timestamp":
                                        newRow["Timestamp"] =  DateTime.ParseExact(splitRow[i], format, CultureInfo.InvariantCulture);
                                        break;
    
                                    case "I_APSS_Modus":
                                         newRow["I_APSS_Modus"] = int.Parse(splitRow[i]);
                                        break;
    
                                    default:
                                        newRow[i] = splitRow[i];
                                        break;
                                }
                            }
                        }
    
                    }
                }
                List<int> data = dt.AsEnumerable().Select(x => x.Field<int>("I_APSS_Modus")).ToList();
            }
        }
     
    }