【问题标题】:Getting error when trying to store csv file contents into a C# Dictionary using CsvHelper尝试使用 CsvHelper 将 csv 文件内容存储到 C# 字典中时出错
【发布时间】:2020-10-16 11:22:44
【问题描述】:

我想使用 C# 和 CsvHelper 库来读取 csv 文件并将其内容存储到字典中。考虑具有以下内容的 Test.csv 文件:

One,1
Two,2
Three,3
Four,4
Five,5

我需要将此 csv 信息放在 Dictionary<string, int> 中,其中键是第一列,值是第二列。 我尝试实现帖子Mapping to a Dictionary 中提出的解决方案,但我在foreach 块中得到了NullReferenceException,因为没有数据被分配到dict 变量中:

using System;
using System.IO;
using System.Globalization;
using System.Collections.Generic;

using CsvHelper;

namespace TestCsvHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var reader = new StreamReader("C:\\Test.csv"))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Read();
                var dict = csv.GetRecord<dynamic>() as IDictionary<string, int>;

                foreach (string key in dict.Keys)
                {
                    Console.WriteLine("Key: {0}, Value: {1}", key, dict[key]);
                }
            }
        }
    }
}

有人可以帮我说明我做错了什么吗?

最好的问候,

法比亚诺

【问题讨论】:

    标签: c# dictionary csvhelper


    【解决方案1】:

    如果转换为Dictionary 有效,csv.GetRecord 只会给你一条记录。 我尝试使用csv.GetRecords 阅读并将其响应转换为Dictionary。 如果这是您所期望的,请检查以下代码:

      static void Main(string[] args)
            {
                using (var reader = new StreamReader("c:\\Test.csv"))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.HasHeaderRecord = false; //since csv does not have headers
                    var dict = csv.GetRecords<dynamic>().ToDictionary(lm=>lm.Field1,lm=>lm.Field2);
    
                    foreach (var key in dict.Keys)
                    {
                        Console.WriteLine("Key: {0}, Value: {1}", key, dict[key]);
                    }
                }
                Console.ReadLine();
           }
    

    【讨论】:

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