Search code examples
c#csvdictionaryfilehelpers

Place csv file into multiple value dictionary in C#


I have a csv file as this:

Name,Gender,Age ,Occupation
Joe,M,29,Doctor
Carl,M,34,Accountant
Bob,M,25,Engineer
Anna,F,32,Model

I wanted to pass this csv file into a dictionary. The key of the dictionary will be the name of the each individual and each key will have hold 3 different values which will be the gender, age and occupation. I am using Filehelper to read the csv file. Here is the class for the csv file:

namespace ReadCSV
{
    [DelimitedRecord(",")]
    [IgnoreFirst(1)]
    public class Orders
    {
        public String Name;

        public String Gender;

        public Int32 Age;

        public String Occupation;
    }
}

Here is main method:

namespace ReadCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            var engine = new FileHelperEngine<Orders>();
            var records = engine.ReadFile("SampleCSV.csv");
            var dict = new Dictionary<String, dynamic>();

            foreach (var record in records)
            {
               //I need to place the csv file into the dictionary here
            }
        }
    }
}

I am not sure how to convert the csv file into a dictionary with multiple values. After I do this, I wanted to retrieve the particular key value pair from the dictionary, for example if I call:

dict["Bob"]["Age"] //ignore the syntax

should return me 25 Thank you very much....


Solution

  • Fill the dictionary like this:

    class Program
    {
        static void Main(string[] args)
        {
            var engine = new FileHelperEngine<Orders>();
            var records = engine.ReadFile("SampleCSV.csv");
    
            // Notice the change here. Only use dynamic if you *really* need it
            var dict = new Dictionary<String, Orders>();
    
            foreach (var record in records)
            {
               //either this:
               dict[record.Name] = record;
    
               //or this:
               dict.Add(record.Name, record);
    
               //(but not both!)
            }
        }
    }
    

    And then reference Bob's age like this:

    var age = dict["Bob"].Age;
    //age will now be 25
    

    You cannot get this:

    var age = dict["Bob"]["Age"];
    

    This is just not how the .Net Dictionary type works, and nothing you do will change that. If you want that kind of lookup ability, you'll have to switch to javascript, implement a special indexer property on your Orders type, or change the dictionary code to create a Dictionary<string, Dictionary<string, Object>>.