Suggest improvement for converting CSV to List<>

McElwain 21 Reputation points
2022-06-21T11:57:12.73+00:00

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));  
        }  
    }  
}  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2022-06-21T12:56:48.477+00:00

    Try something like this:

    fullStats = File.ReadLines(csv_file).Skip(1).Select(line => new DayStats(line.Split(","))).ToList( );


2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2022-06-21T13:05:28.483+00:00

    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);  
            }  
        }  
    }  
    
    1 person found this answer helpful.

  2. McElwain 21 Reputation points
    2022-06-21T12:28:13.337+00:00

    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));
    }
    }

    0 comments No comments