Lumenworks Csv reader Reading columns with the same name or exception "An item with the same key has already been added"

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

The last thing I want is to read all columns, even if there are columns with the same name. I use a custom object to store name value data. Therefore, there is no need to worry about the dictionary causing the same key error. If Lumen-works CSV does not support it, then what can I use ?. Also my CSV file has Json data (with double quotes, commas). I need to handle this too.

+4
source share
1 answer

- - 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)

+3

Source: https://habr.com/ru/post/1569394/


All Articles