简体   繁体   English

将CSV文件放入C#中的多值字典

[英]Place csv file into multiple value dictionary in C#

I have a csv file as this: 我有一个csv文件,如下所示:

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. 我想将此csv文件传递到字典中。 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. 字典的键将是每个人的名字,每个键将具有3个不同的值,分别是性别,年龄和职业。 I am using Filehelper to read the csv file. 我正在使用Filehelper读取csv文件。 Here is the class for the csv file: 这是csv文件的类:

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. 我不确定如何将csv文件转换为具有多个值的字典。 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.... 应该还给我25非常感谢。

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: 然后参考Bob的年龄:

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. .Net词典类型不是这样工作的,您所做的任何更改都不会改变。 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>> . 如果您需要这种查找功能,则必须切换到javascript,在Orders类型上实现特殊的indexer属性,或更改字典代码以创建Dictionary<string, Dictionary<string, Object>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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