-
I am trying to fetch and bind my csv data into a strongly typed class. Something like below However my csv does not have header columns, I would like to bind them using column index and not name. Is there a way to achieve this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There are two ways to accomplish this, by either applying headers to the CSV data, or by adding attributes to the class you are binding to. Assume you have a class you're binding to that looks like the following: class MyRecord
{
public string Name { get; set; }
public int Value { get; set; }
public bool IsActive { get; set; }
} And a CSV file name data.csv containing the following:
Adding headers to CSV.This allows you to essentially attach the missing header row, and will binding by the column name to the property name. // create a schema that defines column names that match the target record type.
var schema = Schema.Parse("Name,Value,IsActive");
var opts = new CsvDataReaderOptions
{
HasHeaders = false,
Schema = new CsvSchema(schema),
};
var csv = CsvDataReader.Create("data.csv", opts);
var records = csv.GetRecords<MyRecord>().ToArray(); Adding attributes the target record.You can add class MyRecord
{
[DataMember(Order = 0)]
public string Name { get; set; }
[DataMember(Order = 1)]
public int Value { get; set; }
[DataMember(Order = 2)]
public bool IsActive { get; set; }
} Then you can bind with the following: var opts = new CsvDataReaderOptions { HasHeaders = false };
var csv = CsvDataReader.Create("data.csv", opts);
var records = csv.GetRecords<MyRecord>().ToArray(); Hopefully that gives you a solution that will work for you. |
Beta Was this translation helpful? Give feedback.
There are two ways to accomplish this, by either applying headers to the CSV data, or by adding attributes to the class you are binding to.
Assume you have a class you're binding to that looks like the following:
And a CSV file name data.csv containing the following:
Adding headers to CSV.
This allows you to essentially attach the missing header row, and will binding by the column name to the property name.