简体   繁体   中英

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

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();
        }
    }
 
}

If you want to stay with CsvHelper, a simple mapping should do the trick:

// Data model of a row (only I_APSS_Modul is of interest)
public class DataSet
{
    public int ApssModus { get; set; }
}

// Mapping
public class ApssMap : ClassMap<DataSet>
{
    public ApssMap()
    {
        Map(m => m.ApssModus).Name("I_APSS_Modus");
    }
}

// Reading records
public void GetMode()
{
    
    string UserCultureInfo = Thread.CurrentThread.CurrentCulture.Name;

    using (var tr = new StreamReader(new FileStream("any.csv", FileMode.Open)))
    {
        using (var csv = new CsvReader(tr, new CsvConfiguration(CultureInfo.CreateSpecificCulture(UserCultureInfo))
        {
            Delimiter = ";"
        }))
        {

            csv.Configuration.RegisterClassMap<ApssMap>();
            var records = csv.GetRecords<DataSet>().ToList();
        }
    }
}

Edit : Check the official docs for all the mapping options: https://joshclose.github.io/CsvHelper/examples/configuration/class-maps

If you just want to read the first row of data, you have to read the header first and then you can read the first data row.

static void Main(string[] args)
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        writer.WriteLine("Timestamp;B_Kurze_Seite;I_Parikeleinfall Reinluft;I_Partikeleinfall Rohluft;I_APSS_Modus");
        writer.WriteLine("2020 06 27 08:49:20:335;FALSE;15;0;0");
        writer.WriteLine("2020 06 27 08:49:20:391;FALSE;0;0;0");
        writer.Flush();
        stream.Position = 0;

        csv.Configuration.Delimiter = ";";

        csv.Read();
        csv.ReadHeader();

        csv.Read();
        var record = csv.GetRecord<dynamic>();

        var APSSModus = record.I_APSS_Modus;
    }
}

Edit: This should give you the same answer as @jdweng

static void Main(string[] args)
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        writer.WriteLine("sep=;");
        writer.WriteLine("");
        writer.WriteLine("");
        writer.WriteLine("");
        writer.WriteLine("Timestamp;B_Kurze_Seite;I_Parikeleinfall Reinluft;I_Partikeleinfall Rohluft;I_APSS_Modus");
        writer.WriteLine("2020 06 27 08:49:20:335;FALSE;15;0;0");
        writer.WriteLine("2020 06 27 08:49:20:391;FALSE;0;0;0");
        writer.Flush();
        stream.Position = 0;

        csv.Configuration.Delimiter = ";";

        csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("sep=") || row.All(string.IsNullOrEmpty);

        var records = csv.GetRecords<dynamic>();

        List<int> data = records.Select(x => (int)int.Parse(x.I_APSS_Modus)).ToList();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM