使用标头指定CSV中的列

时间:2014-10-07 02:23:34

标签: c# csv

是否可以编写一个使用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,我/我将如何使用标题来指定列?

3 个答案:

答案 0 :(得分:1)

您可以从第一行获取标题的索引,即

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

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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];
    }
}