Lumenworks Csv阅读器要读取具有相同名称的列或避免使用“已添加具有相同键的项”。

Raj*_*ddy 5 c# csv lumenworks

I wanted to know if there is any way to make CSV reader read all the columns in the CSV (which will have same column names). I get a An item with the same key has already been added error. I want this to work because my logic is to make a array of similar named columns if it exists and later for each instance of the array element I write further logic.

The final point is I want to be able to read all the columns even if there are columns with same name. I am using a custom object to hold the name value data. So no need to worry about dictionary causing same key exist error. If Lumen-works CSV doesn't support it then what can I use?. Also my CSV file has Json data (with double quotes, comma's) I need to handle this too.

Cor*_*son 3

你把我难住了——我不知道有任何 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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