Importing CSV data into C# classes

前端 未结 7 1339
广开言路
广开言路 2020-12-02 01:45

I know how to read and display a line of a .csv file. Now I would like to parse that file, store its contents in arrays, and use those arrays as values for some classes I cr

7条回答
  •  渐次进展
    2020-12-02 02:37

    splitting the sting into arrays to get the data can be error prone and slow. Try using an OLE data provider to read the CSV as if it were a table in an SQL database, this way you can use a WHERE clause to filter the results.

    App.Config:

    
    
      
        
      
    
    

    program.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.OleDb;
    using System.Configuration;
    using System.Data;
    using System.Data.Common;
    
    namespace CsvImport
    {
        class Stat
        {
            public string Sport { get; set; }
            public DateTime Date { get; set; }
            public string TeamOne { get; set; }
            public string TeamTwo { get; set; }
            public int Score { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                ConnectionStringSettings csv = ConfigurationManager.ConnectionStrings["csv"];
                List stats = new List();
    
                using (OleDbConnection cn = new OleDbConnection(csv.ConnectionString))
                {
                    cn.Open();
                    using (OleDbCommand cmd = cn.CreateCommand())
                    {
                        cmd.CommandText = "SELECT * FROM [Stats.csv]";
                        cmd.CommandType = CommandType.Text;
                        using (OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            int fieldSport = reader.GetOrdinal("sport");
                            int fieldDate = reader.GetOrdinal("date");
                            int fieldTeamOne = reader.GetOrdinal("teamone");
                            int fieldTeamTwo = reader.GetOrdinal("teamtwo");
                            int fieldScore = reader.GetOrdinal("score");
    
                            foreach (DbDataRecord record in reader)
                            {
                                stats.Add(new Stat
                                {
                                    Sport = record.GetString(fieldSport),
                                    Date = record.GetDateTime(fieldDate),
                                    TeamOne = record.GetString(fieldTeamOne),
                                    TeamTwo = record.GetString(fieldTeamTwo),
                                    Score = record.GetInt32(fieldScore)
                                });
                            }
                        }
                    }
                }
    
                foreach (Stat stat in stats)
                {
                    Console.WriteLine("Sport: {0}", stat.Sport);
                }
            }
        }
    }
    

    Here's how the csv should look

    stats.csv:

    sport,date,teamone,teamtwo,score
    basketball,28/01/2011,Rockets,Blazers,98
    baseball,22/08/2011,Yankees,Redsox,4
    

提交回复
热议问题