Reputation: 2421
I am trying to parse a CSV file and extract the first string in each line, or the first column as it is laid out in MS Excel.
I am using CsvParser
with the Read()
method returning a string[]
to the row
variable.
The problem is, it is returning every single value, so my out looks like this for each line:
20070330 00:00 // This is the value I want to reference
0.9312
0.9352
0.9298
0.9343
How can I reference only the values at these positions in the file without putting in a counter to skip the interim values?
using (TextReader reader = File.OpenText(folder))
{
var datesInCsv = new List<string>();
var parsedCsv = new CsvParser(reader);
while (true)
{
var row = parsedCsv.Read();
if (row.IsNullOrEmpty())
{
break;
}
foreach (var date in row)
{
Console.WriteLine(date);
}
Console.ReadLine();
}
}
Upvotes: 1
Views: 4472
Reputation: 216273
The CsvHelper library you are using requires you pass a CsvConfiguration instance when you build the instance of a CsvParse class. This is important to let the library understand and correctly parse your line
The most important thing to give is the value for the Delimiter property. In other words the character used to separate one field from the next one.
You should look at your CSV file and put the appropriate value below.
(For this example I have used the semicolon but change it according to your file)
Looking at you code I think also that the configuration SkipEmptyRecords could be used to simplify the code.
using (TextReader reader = File.OpenText(folder))
{
var datesInCsv = new List<string>();
CsvConfiguration config = new CsvConfiguration();
config.Delimiter = ";";
config.SkipEmptyRecords = true;
var parsedCsv = new CsvParser(reader, config);
string[] row = null;
while ((row = parsedCsv.Read()) != null)
{
// This IsNullOrEmpty doesn't exist according
// to Intellisense and the compiler.
// if(row.IsNullOrEmpty)
// At this point the row is an array of strings where the first
// element is the value you are searching for. No need of loops
Console.WriteLine(row[0]);
Console.ReadLine();
}
}
The Read method of the CsvParser instance returns an array of strings after splitting the input line accordingly to your delimiter. At this point you just need to reference the first element of the array without any loop.
Upvotes: 1
Reputation: 4113
You are explicitly printing every value to the console here:
foreach (var date in row)
{
Console.WriteLine(date);
}
This foreach loop iterates over all elemtens of the current row and print them.
Replace the loop with this, which will only print the first element (index 0):
Console.WriteLine(row[0]);
Of course, this can fail if the line was empty, so you need to check for that, too.
Upvotes: 1
Reputation: 76
You need to "read" the records and pass the argument of the "mapping" you want. Either by index or name.
See here at each section detailed above:
https://joshclose.github.io/CsvHelper/
Upvotes: 0