从稀疏csv文件中提取字典

时间:2017-09-29 00:28:38

标签: c# csv dictionary

我有一个稀疏填充的excel文件,我想在C#中将两列提取到字典中。我尝试了以下内容。读取空行时失败。是否有更清洁的方法来实现同样的目标。我不关心这里的任何其他价值观。只需将AR ID映射到AR Type即可。

     public class Table
    {
        private Dictionary<string, string> _ARID_ARTypeValues = new Dictionary<string, string>();
        private string _arId;

        public Table(string arId)
        {
            _arId = arId;
        }

        public void AddValue(string key, string value)
        {
            _ARID_ARTypeValues.Add(key, value);
        }
    }

    public static IDictionary ParseCsvFile(StreamReader reader)
    {
        Dictionary<string, Table> tables = new Dictionary<string, Table>();

        // First line contains column names.
        var columnNames = reader.ReadLine().Split(',');
        for (int i = 1; i < columnNames.Length; ++i)
        {
            var columnName = columnNames[i];
            var ntable = new Table(columnName);
            if ((columnName == "AR ID") || (columnName == "AR Type"))
            {
                tables.Add(columnName, ntable);
            }
        }

        var line = reader.ReadLine();
        while (line != null)
        {
            var columns = line.Split(',');

            for (int j = 1; j < columns.Length; ++j)
            {
                var table = tables[columnNames[j]];
                table.AddValue(columns[0], columns[j]);
            }
            line = reader.ReadLine();
        }
        return tables;
    }

sample csv

2 个答案:

答案 0 :(得分:1)

我只会使用CSV库,例如CsvHelper,然后用它读取csv文件。

Dictionary<string, string> arIdToArTypeMapping = new Dictionary<string, string>();

using (var sr = File.OpenText("test.csv"))
{
    var csvConfiguration = new CsvConfiguration
    {
        SkipEmptyRecords = true
    };

    using (var csvReader = new CsvReader(sr, csvConfiguration))
    {
        while (csvReader.Read())
        {
            string arId = csvReader.GetField("AR ID");
            string arType = csvReader.GetField("AR Type");

            if (!string.IsNullOrEmpty(arId) && !string.IsNullOrEmpty(arType))
            {
                arIdToArTypeMapping.Add(arId, arType);
            }
        }
    }
}

答案 1 :(得分:1)

您可以使用Cinchoo ETL - 一个开源库来读取csv并将它们转换为字典,就像下面显示的几行代码一样简单

using (var parser = new ChoCSVReader("Dict1.csv")
    .WithField("AR_ID", 7)
    .WithField("AR_TYPE", 8)
    .WithFirstLineHeader(true)
    .Configure(c => c.IgnoreEmptyLine = true)
    )
{
    var dict = parser.ToDictionary(item => item.AR_ID, item => item.AR_TYPE);
    foreach (var kvp in dict)
        Console.WriteLine(kvp.Key + " " + kvp.Value);
}

希望这有帮助。

免责声明:我是这个图书馆的作者。