I am using the CSVHelper library, which can extract a list of objects from a CSV file with just three lines of code:
var streamReader = // Create a reader to your CSV file. var csvReader = new CsvReader( streamReader ); List<MyCustomType> myData = csvReader.GetRecords<MyCustomType>(); However, by file has nonsense lines and I need to skip the first ten lines in the file. I thought it would be nice to use LINQ to ensure 'clean' data, and then pass that data to CsvFReader, like so:
public TextReader GetTextReader(IEnumerable<string> lines) { // Some magic here. Don't want to return null; return TextReader.Null; } public IEnumerable<T> ExtractObjectList<T>(string filePath) where T : class { var csvLines = File.ReadLines(filePath) .Skip(10) .Where(l => !l.StartsWith(",,,")); var textReader = GetTextReader(csvLines); var csvReader = new CsvReader(textReader); csvReader.Configuration.ClassMapping<EventMap, Event>(); return csvReader.GetRecords<T>(); } But I'm really stuck into pushing a 'static' collection of strings through a stream like a TextReaer.
My alternative here is to process the CSV file line by line through CsvReader and examine each line before extracting an object, but I find that somewhat clumsy.