0

Is it possible to write a function that uses the headers in a CSV to specify which column to use?

For example, I have a CSV format:

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

And I have another format:

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

And I wanted The Name, LastName and Address, could I/how would I use the headers to specify the columns?

Ben
  • 2,433
  • 5
  • 39
  • 69

3 Answers3

1

You can get the index of the header from the first line, i.e.

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

then when you're reading the csv line by line look for the nth value to get the value of the name, i.e

string name = csvLine.Split(',')[indexOfName];
artm
  • 8,554
  • 3
  • 26
  • 43
0

You might also want to load it first into a datatable as shown here. You can then filter which you need.

Community
  • 1
  • 1
bodjo
  • 326
  • 1
  • 5
0

Could write a little class to help you out that would map the column names to the indices (this is untested but should be pretty close)

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];
    }
}
Chad Schouggins
  • 3,440
  • 2
  • 23
  • 29