Try something like this:
fullStats = File.ReadLines(csv_file).Skip(1).Select(line => new DayStats(line.Split(","))).ToList( );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
This small class is just a List<> of objects, where each object represents a single line from a CSV. I'm wondering if there is a better way. For example, can the foreach somehow be included in the var data ... declaration? Of course, I do understand this is not production ready without error checking etc. I'm just mainly interested in the most efficient solution.
public class History
{
public List<DailyStats> fullStats = new List<DailyStats>();
public History(string csv_file)
{
var data = File.ReadAllLines(csv_file).Skip(1).Select(a => a.Split(","));
foreach (var line in data)
{
fullStats.Add(new DailyStats(line));
}
}
}
Try something like this:
fullStats = File.ReadLines(csv_file).Skip(1).Select(line => new DayStats(line.Split(","))).ToList( );
I would recommend using CsvHelper available from NuGet which in the following code sample handles exceptions if any written to a text file.
public (bool success, List<DailyStats>) ReaDailyStatsList(string fileName)
{
List<DailyStats> list = new();
StringBuilder errorBuilder = new();
var configuration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Encoding = Encoding.UTF8,
Delimiter = ",",
HasHeaderRecord = true, // skip first line
};
using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var textReader = new StreamReader(fs, Encoding.UTF8))
using (var csv = new CsvReader(textReader, configuration))
{
while (csv.Read())
{
try
{
var record = csv.GetRecord<DailyStats>();
list.Add(record);
}
catch (Exception ex)
{
errorBuilder.AppendLine(ex.Message);
}
}
}
if (errorBuilder.Length > 0)
{
errorBuilder.Insert(0, $"Errors for {fileName}\n");
File.WriteAllText(
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "ParseErrors.txt"),
errorBuilder.ToString());
return (false, null);
}
else
{
return (true, list);
}
}
}
Well, I think I might have had my Aha! moment finally just minutes after posting the question (see constructor changes below), but I would still appreciate any suggestions,
public History(string csv_file)
{
foreach (var line in File.ReadLines(csv_file).Skip(1).Select(a => a.Split(",")))
{
fullStats.Add(new DayStats(line));
}
}