Replies: 5 comments
-
A slight change to public class CarFleet
{
public Velocity Car1 { get; set; }
public Velocity Car2 { get; set; }
} You can use using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader))
{
csv.Configuration.Delimiter = ",";
writer.WriteLine("car1_speed,car1_direction,car2_speed,car2_direction");
writer.WriteLine("45.2,56.3,35.2,64.1");
writer.Flush();
stream.Position = 0;
csv.Configuration.ReferenceHeaderPrefix = (type, name) => $"{name}_";
csv.Configuration.PrepareHeaderForMatch = (header, index) => header.ToLower();
csv.Configuration.AutoMap<CarFleet>();
var records = csv.GetRecords<CarFleet>();
} |
Beta Was this translation helpful? Give feedback.
-
Using Nonetheless, I can modify to the real version of |
Beta Was this translation helpful? Give feedback.
-
I am not the expert on this. I have been answering questions mainly to increase my own knowledge. There was an issue very similar to yours, but Josh only showed it was possible to map a single public class CarFleet
{
public int Id { get; set; }
public string Name { get; set; }
public List<Velocity> Cars { get; set; }
}
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader))
{
csv.Configuration.Delimiter = ",";
writer.WriteLine("Id,Name,car1_speed,car1_direction,car2_speed,car2_direction");
writer.WriteLine("1,name,45.2,56.3,35.2,64.1");
writer.Flush();
stream.Position = 0;
var records = new List<CarFleet>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
var record = csv.GetRecord<CarFleet>();
record.Cars = new List<Velocity>();
Velocity car = null;
for (var i = 2; i < csv.Context.HeaderRecord.Count(); i++)
{
if (i % 2 == 0)
{
car = new Velocity
{
Speed = csv.GetField<float>(i)
};
}
else
{
car.Direction = csv.GetField<float>(i);
record.Cars.Add(car);
}
}
records.Add(record);
}
} |
Beta Was this translation helpful? Give feedback.
-
I admit I did not read the doco, but I did not realise the Property name casing had to match the headers. |
Beta Was this translation helpful? Give feedback.
-
@enheh Are there a set number of cars on each row, or does it vary? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
If I try to use a class map to read values into a
List<ReferenceType>
property,with something like this:
I get a runtime exception like this: "Property 'Single Speed' is not defined for type 'CarFleet'"
I've looked all through the test cases and can't seem to find anything analogous. Is there some way to make this work?
Beta Was this translation helpful? Give feedback.
All reactions