Ben
Ben

Reputation: 2523

Using headers to specifiy columns in CSV

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?

Upvotes: 0

Views: 823

Answers (3)

Chad Schouggins
Chad Schouggins

Reputation: 3521

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

Upvotes: 0

bodjo
bodjo

Reputation: 326

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

Upvotes: 0

artm
artm

Reputation: 8584

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

Upvotes: 1

Related Questions