流明工程 csv 阅读器 读取具有相同名称的列或避免“已添加具有相同键的项目”

本文关键字:添加 项目 csv 读取 | 更新日期: 2023-09-27 18:35:35

我想知道是否有任何方法可以让CSV阅读器读取CSV中的所有列(它们将具有相同的列名)。我收到一个An item with the same key has already been added错误。我希望这能工作,因为我的逻辑是制作一个类似的命名列数组(如果存在),稍后我为数组元素的每个实例编写进一步的逻辑。

最后一点是我希望能够读取所有列,即使有同名的列。我正在使用自定义对象来保存名称值数据。因此,无需担心字典会导致相同的键存在错误。如果Lumen-works CSV不支持它,那么我可以使用什么?此外,我的 CSV 文件有 Json 数据(带双引号、逗号),我也需要处理这个问题。

流明工程 csv 阅读器 读取具有相同名称的列或避免“已添加具有相同键的项目”

你难倒了我 - 我不知道有任何CSV解析器可以解释重复的列标题,我已经测试了其中的很多。不过,有一些CSV解析器将为您提供原始列数据,并且通过一些腿部工作,您可以将其用作构建块,以使数据进入更友好的状态。

这将返回一个Dictionary<string, List<string>>序列,每条记录一个,键是标题,列表是具有相同标题的所有列:

using System.IO;
using System.Collections.Generic;
using Ctl.Data;
static IEnumerable<Dictionary<string, List<string>>> ReadCsv(string filePath)
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        CsvReader csv = new CsvReader(sr);
        // first read in the header.
        if (!csv.Read())
        {
            yield break; // an empty file, break out early.
        }
        RowValue header = csv.CurrentRow;
        // now the records.
        while (csv.Read())
        {
            Dictionary<string, List<string>> dict =
                new Dictionary<string, List<string>>(header.Count);
            RowValue record = csv.CurrentRow;
            // map each column to a header value
            for (int i = 0; i < record.Count; ++i)
            {
                // if there are more values in the record than the header,
                // assume an empty string as header.
                string headerValue = (i < header.Count ? header[i].Value : null)
                    ?? string.Empty;
                // get the list, or create if it doesn't exist.
                List<string> list;
                if (!dict.TryGetValue(headerValue, out list))
                {
                    dict[headerValue] = list = new List<string>();
                }
                // finally add column value to the list.
                list.Add(record[i].Value);
            }
            yield return dict;
        }
    }
}

我对Lumenworks不够熟悉 - 它使用Ctl.Data,我知道只要正确引用,就可以允许格式化的JSON数据和列中的任何其他奇怪之处。(免责声明:我是Ctl.Data的作者)

这在LumenWorks 4.0中得到了支持,这要归功于jonreis。

参见LumenWorks.Framework.Tests.Unit/IO/Csv/CsvReaderTest.cs

    using (CsvReader csvReader = new CsvReader(new StringReader("Header,Header'r'nValue1,Value2"), true))
        {
          csvReader.DuplicateHeaderEncountered += (s, e) => e.HeaderName = $"{e.HeaderName}_{e.Index}";