I have a CSV file which looks like this basically:
TransactionID ProfileID Date // more columns here...
somevalue 123123123 somedate
somevalue 123123123 somedate
somevalue 123123123 somedate
somevalue 123123123 somedate
somevalue 123123123 somedate
I would like to extract only specific columns which are ProfileID and Date out of all these columns from the CSV file, either by mapping it to an existing class like this:
public class MyMappedCSVFile
{
public string ProfileID { get; set; }
public string Date { get; set; }
}
Or by storing it in a Dictionary collection?
I have tried something like this:
public static List<string> ReadInCSV(string absolutePath)
{
List<string> result = new List<string>();
string value;
using (TextReader fileReader = File.OpenText(absolutePath))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
while (csv.Read())
{
for (int i = 0; csv.TryGetField<string>(i, out value); i++)
{
result.Add(value);
}
}
}
return result;
}
But this takes out everything out of the CSV file, literally everything in a single List, and it's not what I want...
Can someone help me out with this ?
The header is still to skip in this code, but with this code, you can choose which columns to extract. It might be much faster if you use a StreamReader. And you will need a constructor for your object.
Code for your Object:
CvsHelper is a nice package you can use for this sort of thing, it lets you get by index or name.
An example from the documents is
The docs give lots of examples of reading the file and iterating over it, and mapping to classes and so on. Seems perfect for this.
https://github.com/JoshClose/CsvHelper
Here is a more complete answer to your solution in realtion to reading (as you have installed the package)
records will be a list of your CSV rows mapped to your object.
Hi You may use this code snippets to read any kind of csv file with little customization according to your needs.
filePath is the path for your csv file