【问题标题】:Using headers to specifiy columns in CSV使用 CSV 中特定列的标题
【发布时间】:2014-10-07 11:01:58
【问题描述】:

是否可以编写一个函数,使用 CSV 中的标题来指定要使用的列?

例如,我有一个 CSV 格式:

Name,LastName,Age,Address
Bob,Green,26,123 This Street
Jane,Doe,35,234 That Street

我还有另一种格式:

LastName,Name,Address,Age
Brown,Dave,123 Other Street,17
Jane,Doe,234 That Other Street,35

我想要NameLastNameAddress,我可以/我如何使用标题来指定列吗?

【问题讨论】:

    标签: c# csv


    【解决方案1】:

    可以从第一行获取表头的索引,即

    int indexOfName = firstLineOfCSV.Split(',').ToList().IndexOf("Name");
    

    然后当您逐行读取 csv 时,查找第 n 个值以获取名称的值,即

    string name = csvLine.Split(',')[indexOfName];
    

    【讨论】:

      【解决方案2】:

      您可能还想先将其加载到数据表中,如here 所示。然后你可以过滤你需要的。

      【讨论】:

        【解决方案3】:

        可以编写一个小类来帮助您将列名映射到索引(这是未经测试的,但应该非常接近)

        class Csv
        {
            // Maps the column names to indices
            Dictionary<String, int> columns = new Dictionary<String, int>();
            // Store rows as arrays of fields
            List<String[]> rows = new List<String[]>()
        
            public Csv(String[] lines)
            {
                String[] headerRow = lines[0].Split(',');
        
                for (int x = 0; x < headerRow.Length; x += 1)
                {
                    // Iterate through first row to get the column names an map to the indices
                    String columnName = headerRow[x];
                    columns[columnName] = x;
                }
        
                for (int x = 1; x < lines.Length - 1; x += 1)
                {
                    // Iterate through rows splitting them into each field and storing in 'rows' variable
                    rows.Add(lines[x].Split(','); // Not properly escaping (e.g. address could have "Memphis, Tn")
                }
            }
        
            // Method to get a field by row index and column name
            public Get(int rowIndex, String columnName)
            {
                int columnIndex = columns[columnName];
        
                return rows[rowIndex][columnIndex];
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多