首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lumenworks Csv读取器读取相同名称的列或避免使用相同键的项已经添加

Lumenworks Csv读取器读取相同名称的列或避免使用相同键的项已经添加
EN

Stack Overflow用户
提问于 2014-12-30 07:13:17
回答 2查看 4.2K关注 0票数 6

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-30 07:41:40

你把我搞糊涂了--我不知道有哪个CSV解析器能解释重复的列标题,而且我测试了其中很多。还有CSV解析器,它将为您提供原始的列数据,通过一些腿的工作,您可以使用它作为构建块,使您的数据进入更友好的状态。

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

代码语言:javascript
复制
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的作者)

票数 3
EN

Stack Overflow用户

发布于 2019-08-03 22:19:26

由于jonreis的支持,这在LumenWorks 4.0中得到了支持。

请参阅LumenWorks.Framework.Tests.Unit/IO/Csv/CsvReaderTest.cs

代码语言:javascript
复制
    using (CsvReader csvReader = new CsvReader(new StringReader("Header,Header\r\nValue1,Value2"), true))
        {
          csvReader.DuplicateHeaderEncountered += (s, e) => e.HeaderName = $"{e.HeaderName}_{e.Index}";
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27701134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档