Parse a fixed width file with an array of objects?

69 views Asked by At

Let's say I have a this fixed length string:

ABBCCC10purple crayon5 red    pencil9 green  marker

The A, B, and C fields are easily mapped:

[FixedLengthRecord]
public class OutterRecord
{
    [FieldFixedLength(1)]
    public string AField { get; set; }

    [FieldFixedLength(2)]
    public string BField { get; set; }

    [FieldFixedLength(3)]
    public string CField { get; set; }
}

However, the remaining part of the line is an array of objects. For example, let's say 10purple crayon is:

[FixedLengthRecord]
public class WritingInstrument
{
    [FieldFixedLength(2)]
    public string Count { get; set; }

    [FieldFixedLength(7)]
    public string Color { get; set; }

    [FieldFixedLength(6)]
    public string TypeOfInstrument { get; set; }
}

Is there a way in FileHelpers to parse the WritingIntsturments section? Given the constraint/limitation that each individual WritingInstrument record is a max of 15 characters wide, and there can be at most 10 items in the array.

I want the resulting deserialized object to look like this:

[FixedLengthRecord]
public class OutterRecord
{
    [FieldFixedLength(1)]
    public string AField { get; set; }

    [FieldFixedLength(2)]
    public string BField { get; set; }

    [FieldFixedLength(3)]
    public string CField { get; set; }

    [SomeTypeOfFixedArray(10)]
    List<WritingInstrument> WritingInstruments { get; set; }
}
1

There are 1 answers

1
shamp00 On

You can just declare a field of type string[].

Here's a working program:

[FixedLengthRecord()]
public class OutterRecord
{
    [FieldFixedLength(1)]
    public string AField { get; set; }

    [FieldFixedLength(2)]
    public string BField { get; set; }

    [FieldFixedLength(3)]
    public string CField { get; set; }

    [FieldFixedLength(15)]
    public string[] WritingInstruments { get; set; }
}

internal class Program
{
    static void Main(string[] args)
    {
        var engine = new FixedFileEngine<OutterRecord>();
        var records = engine.ReadString("ABBCCC10purple crayon5 red    pencil9 green  marker");

        Assert.AreEqual("A", records[0].AField);
        Assert.AreEqual("BB", records[0].BField);
        Assert.AreEqual("CCC", records[0].CField);
        Assert.AreEqual("10purple crayon", records[0].WritingInstruments[0]);
        Assert.AreEqual("5 red    pencil", records[0].WritingInstruments[1]);
        Assert.AreEqual("9 green  marker", records[0].WritingInstruments[2]);

        Console.WriteLine("All OK");
        Console.ReadKey();
    }
}