尝试使用 CsvHelper 将 csv 文件内容存储到 C# 字典时出错
Getting error when trying to store csv file contents into a C# Dictionary using CsvHelper
我想使用 C# 和 CsvHelper 库读取 csv 文件并将其内容存储到字典中。考虑具有以下内容的 Test.csv 文件:
One,1
Two,2
Three,3
Four,4
Five,5
我需要的是将此 csv 信息放在 Dictionary<string, int>
中,其中键是第一列,值是第二列。
我试图实现 post Mapping to a Dictionary 中提出的解决方案,但我在 foreach 块中得到 NullReferenceException,因为 none 数据被分配到 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]);
}
}
}
}
}
有人可以帮我指出我做错了什么吗?
此致,
法比亚诺
如果转换为 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();
}
我想使用 C# 和 CsvHelper 库读取 csv 文件并将其内容存储到字典中。考虑具有以下内容的 Test.csv 文件:
One,1
Two,2
Three,3
Four,4
Five,5
我需要的是将此 csv 信息放在 Dictionary<string, int>
中,其中键是第一列,值是第二列。
我试图实现 post Mapping to a Dictionary 中提出的解决方案,但我在 foreach 块中得到 NullReferenceException,因为 none 数据被分配到 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]);
}
}
}
}
}
有人可以帮我指出我做错了什么吗?
此致,
法比亚诺
如果转换为 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();
}