【问题标题】:Place csv file into multiple value dictionary in C#将csv文件放入C#中的多值字典中
【发布时间】:2017-11-08 06:09:53
【问题描述】:

我有一个这样的 csv 文件:

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

我想将此 csv 文件传递​​到字典中。字典的键是每个人的名字,每个键都有 3 个不同的值,分别是性别、年龄和职业。我正在使用 Filehelper 读取 csv 文件。这是 csv 文件的类:

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

        public String Gender;

        public Int32 Age;

        public String Occupation;
    }
}

这里是主要方法:

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
            }
        }
    }
}

我不确定如何将 csv 文件转换为具有多个值的字典。完成此操作后,我想从字典中检索特定的键值对,例如,如果我调用:

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

应该回复我25 非常感谢……

【问题讨论】:

    标签: c# csv dictionary filehelpers


    【解决方案1】:

    像这样填写字典:

    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!)
            }
        }
    }
    

    然后像这样引用 Bob 的年龄:

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

    你不能得到这个:

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

    这不是 .Net Dictionary 类型的工作原理, 您所做的任何事情都不会改变这一点。如果你想要这种查找能力,你必须切换到 javascript,在你的 Orders 类型上实现一个特殊的索引器属性,或者更改字典代码以创建一个 Dictionary&lt;string, Dictionary&lt;string, Object&gt;&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2021-03-06
      相关资源
      最近更新 更多