I’m working with a simple text file containing car data, and I’d like to parse it into strongly typed objects in C#.
The file structure looks like this:
Brand;Model;FuelType;Year;Price Toyota;Corolla;Petrol;2018;15000 Ford;Focus;Diesel;2016;12000In some cases, multiple records may appear on the same line separated by spaces.
My goal is to keep the code easy to read and maintain, not just make it work.
What would be a clean and understandable way to:
read the file
parse the data
store it in a list of objects
Here is my approach:
using System; using System.Collections.Generic; using System.IO; namespace Assignment { internal class Car { public string Brand { get; set; } public string Model { get; set; } public string FuelType { get; set; } public int Year { get; set; } public int Price { get; set; } public Car(string brand, string model, string fuelType, int year, int price) { Brand = brand; Model = model; FuelType = fuelType; Year = year; Price = price; } public static ListReadFromFile() { List cars = new List (); // Read all lines (first line is header) string[] lines = File.ReadAllLines("cars.txt"); for (int i = 1; i < lines.Length; i++) { // A line may contain multiple records separated by space string[] records = lines[i].Split(' '); for (int j = 0; j < records.Length; j++) { // Each record is separated by semicolon string[] data = records[j].Split(';'); Car car = new Car( data[0], data[1], data[2], int.Parse(data[3]), int.Parse(data[4]) ); cars.Add(car); } } return cars; } } } Is this considered good practice? How could it be improved for readability?