CSV to Generic List

by clayshannon

HTML

<h2>More CSV Files Than You Can Shake a Stick At</h2>
<p>It has been estimated that there are more CSV files floating around the Internet and stashed within the innards of hard drives than there are longhorns in Laredo or Sylvester Stallone movie sequels. That being the case, you may want to make use of those hordes of data by making the content of those files available in the form of a collection of easily traversable data. So why not parse them and store their contents in a generic list?</p>

<p>It's easy - say you have a class named Platypus defined like so:</p>

<pre lang="cs">
    public class Platypus
    {
        // These are the column names in PlatypusN.csv:
        // id, duckbill_name, billLength, poisonToeLength, description
        public int Id { get; set; }
        public String duckbill_name { get; set; }
        public double billLength { get; set; }
        public double poisonToeLength { get; set; }
        public String description { get; set; }
    }
</pre>

<p>You can now write a method to open the CSV file, parse it, and populate the appropriate generic list, like so:</p>
    
<pre lang="cs">
        public List<Platypus> GetPlatypus(string pondNum)
        {
            List<Platypus> platypus = new List<Platypus>();
            const String PlatypusBase = @"C:\Duckbills\PlatypusPalace{0}.csv";

            String fileToLoad = String.Format(PlatypusBase, pondNum);
            using (StreamReader r = new StreamReader(fileToLoad))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    // Skip the column row
                    if (parts[0] == "id") continue;
                    Platypus dbp = new Platypus();
                    dbp.Id = Convert.ToInt32(parts[0]);
                    dbp.duckbillName = parts[1];
                    dbp.billSize = Convert.ToInt32(parts[2]);
                    dbp.poisonToeSize...