[Solved] In C#, what is the best way to read in a text file with thiis format and convert to list of objects?


The main problem is the presence of the category name before the headers and data. This creates a condition to consider while looping over the lines because when we read a category name we need to consider 4 rows while when reading the transaction data we have to loop over 3 rows.

However there is a pattern in the data that we could exploit with a normal loop. If every 3 rows we can convert the line to a datetime then we could procede to create a BankTransaction with the other two lines, otherwise we could read the category name and skip the next 3 lines.

List<BankTransaction> result = new List<BankTransaction>();
string currentCat = string.Empty;

for (int x = 0; x < lines.Length; x += 3)
{
    DateTime dt;
    string line = lines[x];

    // If we can convert the line to a date, we are to the beginning
    // of a BankTransaction for the current category
    if (DateTime.TryParse(line, out dt))
    {
        // We never enter this if on the first line 
        // according to your sample text.
        BankTransaction bt = new BankTransaction()
        {
            Date = dt,
            Description = lines[x+1],
            Amount = Convert.ToDecimal(lines[x+2]),
            Category = currentCat
        };
        result.Add(bt);
    }
    else
    {
        // We are on the category line, get the name and add 
        // 1 more line to the 3 skipped in the loop
        currentCat = line;
        x++;
    }
}

solved In C#, what is the best way to read in a text file with thiis format and convert to list of objects?